整理两个日期的方法。
根据日期获取当天是周几
/**
* 根据日期获取当天是周几
* @param datetime 日期
* @return 周几
*/
public static String dateToWeek(String datetime) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
Calendar cal = Calendar.getInstance();
Date date;
try {
date = sdf.parse(datetime);
cal.setTime(date);
} catch (ParseException e) {
e.printStackTrace();
}
int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
return weekDays[w];
}
获取某段时间内的周一(二等等)的日期
/**
* 获取某段时间内的周一(二等等)的日期
* @param dataBegin 开始日期
* @param dataEnd 结束日期
* @param weekDays 获取周几,1-6代表周一到周六。0代表周日
* @return 返回日期List
*/
public static List<String> getDayOfWeekWithinDateInterval(String dataBegin, String dataEnd, int weekDays) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
List<String> dateResult = new ArrayList<>();
Calendar cal = Calendar.getInstance();
String[] dateInterval = {dataBegin, dataEnd};
Date[] dates = new Date[dateInterval.length];
for (int i = 0; i < dateInterval.length; i++) {
String[] ymd = dateInterval[i].split("[^\\d]+");
cal.set(Integer.parseInt(ymd[0]), Integer.parseInt(ymd[1]) - 1, Integer.parseInt(ymd[2]));
dates[i] = cal.getTime();
}
for (Date date = dates[0]; date.compareTo(dates[1]) <= 0; ) {
cal.setTime(date);
if (cal.get(Calendar.DAY_OF_WEEK) - 1 == weekDays) {
String format = sdf.format(date);
dateResult.add(format);
}
cal.add(Calendar.DATE, 1);
date = cal.getTime();
}
return dateResult;
}
计算获取相隔固定时间段的时间
/**
* 根据时间间隔,算出后面的时间。例如,24时,分成3部分,每个时间间隔是8小时
* 然后,初始时间加上8小时,得到新的时间,新的时间再加上8小时,得到另一个时间,依此类推
* @param totalHours 计算的总小时数
* @param part 将总小时分成的分数
* @param initTime 初始时间
* @return 计算后的时间列表
*/
public static List<LocalDateTime> getGapTime(int totalHours, int part, LocalDateTime initTime) {
if (totalHours == 0) totalHours = 24;
if (part == 0) part = 1;
if (initTime == null) initTime = LocalDateTime.now();
long gap = totalHours / part;
List<LocalDateTime> timeList = Lists.newArrayList();
for (int i = 0; i < part; i++) {
long newGap = gap * i;
LocalDateTime newTime = initTime.plusHours(newGap);
timeList.add(newTime);
}
return timeList;
}
/**
* 根据天数获取第几周的第几天
* @param startDate 时间参考基数
* @return 第3周-4
*/
public static String getWeekAndDays(LocalDate startDate, LocalDate endDate) {
//时间段内天数
Long between = endDate.toEpochDay() - startDate.toEpochDay();
between++;
int weeks = (int) (Math.ceil(between * 1.0 / 7));
long days = between.intValue() % 7 == 0 ? 7 : between % 7;
return new StringBuffer("第").append(weeks).append("周").append( "-").append(days).toString();
}