获取当天,本周,本月的起始时间
LocalDate today = LocalDate.now();// 取当前日期
LocalDate inputDate = LocalDate.parse(formatter(today));
//当天的
System.out.println(ToStringPattern(getBeginOfDay(ToDatePattern(formatter(today)))));//2018-03-21 00:00:00
System.out.println(ToStringPattern(getEndOfDay(ToDatePattern(formatter(today)))));//2018-03-21 23:59:59
//本周的第一天
TemporalAdjuster FIRST_OF_WEEK = TemporalAdjusters.ofDateAdjuster(localDate -> localDate.minusDays(localDate.getDayOfWeek().getValue() - DayOfWeek.MONDAY.getValue()));
System.out.println(inputDate.with(FIRST_OF_WEEK));
System.out.println(ToStringPattern(getBeginOfDay(ToDatePattern(formatter(inputDate.with(FIRST_OF_WEEK))))));//2018-03-19 00:00:00
//本周的最后一天
TemporalAdjuster LAST_OF_WEEK = TemporalAdjusters.ofDateAdjuster(localDate -> localDate.plusDays(DayOfWeek.SUNDAY.getValue() - localDate.getDayOfWeek().getValue()));
System.out.println(inputDate.with(LAST_OF_WEEK));
System.out.println(ToStringPattern(getEndOfDay(ToDatePattern(formatter(inputDate.with(LAST_OF_WEEK))))));//2018-03-25 23:59:59
// 取本月第1天:
LocalDate firstDayOfThisMonth = today.with(TemporalAdjusters.firstDayOfMonth()); // 2014-12-01
System.out.println(firstDayOfThisMonth);
System.out.println(ToStringPattern(getBeginOfDay(ToDatePattern(formatter(firstDayOfThisMonth)))));//2018-03-01 00:00:00
// 取本月最后一天,再也不用计算是28,29,30还是31:
LocalDate lastDayOfThisMonth = today.with(TemporalAdjusters.lastDayOfMonth()); // 2014-12-31
System.out.println(ToStringPattern(getEndOfDay(ToDatePattern(formatter(lastDayOfThisMonth)))));//2018-03-31 23:59:59
String转化为Date
public static Date ToDatePattern(String convertString) {
Date result = null;
if (!org.springframework.util.StringUtils.isEmpty(convertString)) {
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
sdf.setLenient(false);
result = sdf.parse(convertString);
} catch (Exception ex) {
}
} else {
}
return result;
}
Date转化为String
public static String ToStringPattern(Date date){
String result=null;
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
result=sdf.format(date);
} catch (Exception ex) {
}
return result;
}
localDate转化Date
public static String formatter(LocalDate localDate) {
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
return localDate.format(dateTimeFormatter);
}
获取指定日期的起始时间
public static Date getBeginOfDay(Date date) {
Calendar cursorCal = Calendar.getInstance();
cursorCal.setTime(date);
cursorCal.set(Calendar.HOUR_OF_DAY, 0);
cursorCal.set(Calendar.MINUTE, 0);
cursorCal.set(Calendar.SECOND, 0);
return cursorCal.getTime();
}
获取指定日期的结束时间
public static Date getEndOfDay(Date date) {
Calendar cursorCal = Calendar.getInstance();
cursorCal.setTime(date);
cursorCal.set(Calendar.HOUR, 23);
cursorCal.set(Calendar.MINUTE, 59);
cursorCal.set(Calendar.SECOND, 59);
return cursorCal.getTime();
}