简单记录一下。
mysql数据库,字段类型datetime,代码用用LocalDateTime.now()来获取当前时间并存储。
坑:
LocalDateTime.now()获取到的时间包含年、月、日、时、分、秒、纳秒,由于数据库是datetime,只到秒,入库的时候会根据纳秒进行四舍五入。例如LocalDateTime.now()拿到的是019-11-20T21:08:13.723,但是入库的时候会是2019-11-20 21:08:14,在极端情况下会出现问题,这个要看具体场景。
解决办法很简单:
通过LocalDateTime的withNano()方法,直接舍弃纳秒。
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
System.out.println(now);
System.out.println(now.withNano(0));
}
输出:
2019-11-20T21:11:03.752
2019-11-20T21:11:03
题外:
// LocalDateTime由LocalDate「日期部分」和LocalTime「时间部分」组成
private LocalDateTime(LocalDate date, LocalTime time) {
this.date = date;
this.time = time;
}
// 日期部分:年、月、日
private LocalDate(int year, int month, int dayOfMonth) {
this.year = year;
this.month = (short) month;
this.day = (short) dayOfMonth;
}
// 时间部分:时、分、秒、纳秒
private LocalTime(int hour, int minute, int second, int nanoOfSecond) {
this.hour = (byte) hour;
this.minute = (byte) minute;
this.second = (byte) second;
this.nano = nanoOfSecond;
}
网友评论