标签:时间类 技术 cond null span eid def ati param
1、问题描述:
我获取当天最大的时间:
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()); }
获取最大的时间插入到数据库中,总是多一秒,例如现在时间是2018-04-26 22:00:01 获取的最大的时间为:2018-04-26 23:59:59 这里可以查看time的源码:
设置MAX的源码:
static { for (int i = 0; i < HOURS.length; i++) { HOURS[i] = new LocalTime(i, 0, 0, 0); } MIDNIGHT = HOURS[0]; NOON = HOURS[12]; MIN = HOURS[0]; MAX = new LocalTime(23, 59, 59, 999_999_999); }
插入到数据库之后变为 2018-04-27 00:00:00 ,很奇怪的多加了一秒,经过查资料发现:MySQL数据库对于毫秒大于500的数据会进位!!!
2、解决办法
我把最后一位毫秒变为0 了,通过看java时间类的源码,查找到of是设置时间的,
/** * Obtains an instance of {@code LocalTime} from an hour, minute, second and nanosecond. * <p> * This returns a {@code LocalTime} with the specified hour, minute, second and nanosecond. * * @param hour the hour-of-day to represent, from 0 to 23 * @param minute the minute-of-hour to represent, from 0 to 59 * @param second the second-of-minute to represent, from 0 to 59 * @param nanoOfSecond the nano-of-second to represent, from 0 to 999,999,999 * @return the local time, not null * @throws DateTimeException if the value of any field is out of range */ public static LocalTime of(int hour, int minute, int second, int nanoOfSecond) { HOUR_OF_DAY.checkValidValue(hour); MINUTE_OF_HOUR.checkValidValue(minute); SECOND_OF_MINUTE.checkValidValue(second); NANO_OF_SECOND.checkValidValue(nanoOfSecond); return create(hour, minute, second, nanoOfSecond); }
所以我修改后的获取当天最大的时间的代码为:
/** * 获取当天最大时间 23:59:59 * new LocalTime(23, 59, 59, 999_999_999) * 不设置为最大的值,因为设置为最大的值后,mysql(有些版本的)会对插入的时间的毫秒值大于500的进位操作,所以在此地设置毫秒值为0. * @param date * @return */ public static Date getEndOfDay(Date date) { LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(date.getTime()), ZoneId.systemDefault());; LocalDateTime endOfDay = localDateTime.with(LocalTime.of(23,59,59,0)); return Date.from(endOfDay.atZone(ZoneId.systemDefault()).toInstant()); }
验证了一下,ok了。
参考:https://my.oschina.net/u/2353881/blog/1573811
标签:时间类 技术 cond null span eid def ati param
原文地址:https://www.cnblogs.com/lixiaochao/p/8955312.html