需求:
1.前端传递过来yyyy-MM的Date类型的日期,会自动转化成yyyy-mm-01:00:00:00,然而我需要把后面的拼接成yyyy-mm-本月最后一天:23:59:59
2.获取当天的最小时间何最大时间
使用localDate能解决这个问题
思路:首先把localdate变成本月最后一天,然后把它转化成字符串,再拼接上:23:59:59,再转化成日期格式。
public static Date cover(Date date){
Instant ins=date.toInstant();
//设置时区
ZoneId zd=ZoneId.systemDefault();
//把转化成localdate
LocalDate localDate=ins.atZone(zd).toLocalDate();
String localString=localDate.with(TemporalAdjusters.lastDayOfMonth())+":23"+":59"+":59";
return new SimpleDateFormat("yyyy-MM-dd:HH:mm:ss").parse(localString);
}
public class GetMaxMinTime {
public static void main(String[] args) {
Date date = new Date();
System.out.println("今天开始时间:" + getStartOfDay(date));
System.out.println("今天结束时间:" + getEndOfDay(date));
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(sdf.format(getStartOfDay(date)));
System.out.println(sdf.format(getEndOfDay(date)));
}
// 获得某天最大时间 2017-10-15 23:59:59
public static Date getEndOfDay(Date date) {
LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(date.getTime()), ZoneId.systemDefault());;
LocalDateTime endOfDay = localDateTime.with(LocalTime.MAX);
return Date.from(endOfDay.atZone(ZoneId.systemDefault()).toInstant());
}
// 获得某天最小时间 2017-10-15 00:00:00
public static Date getStartOfDay(Date date) {
LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(date.getTime()), ZoneId.systemDefault());
LocalDateTime startOfDay = localDateTime.with(LocalTime.MIN);
return Date.from(startOfDay.atZone(ZoneId.systemDefault()).toInstant());
}
}
网友评论