mysql插入的时候会增加一秒

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

转载于:https://www.cnblogs.com/lixiaochao/p/8955312.html

转载于:https://blog.csdn.net/weixin_34092370/article/details/93287741

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值