mysql插入的時間莫名的加一秒
阿新 • • 發佈:2018-04-27
發現 sql 毫秒 present turn 操作 OS pre .net
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
mysql插入的時間莫名的加一秒