时间戳转 Date 字符串出现误差

  1. 问题描述:
  
  前台一个日期选择组件,提交的数据格式为“1991-05-10”,后台使用 SimpleDateFormat 进行转换,获取到时间戳,存入数据库,数据库字段为 bigint 类型,保存后,日期回显,显示为 “1991-05-09”,出现一天的误差,但不是所有日期都存在误差。
  前台获取到时间戳,转换后调用 toLocaleDateString 回显数据。
  
  2. 解决方法:
  
  后台,在使用 SimpleDateFormat 时,设置时区,如下:
  

simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));

  3. 相关代码如下:
  

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
            Date birthdayDate = null;
            try {
                birthdayDate = simpleDateFormat.parse(birthday);
                long time = birthdayDate.getTime();
                long l = time / 1000;
                member.setBirthday(l);
            } catch (ParseException e) {
                LOGGER.error("出生日期转换异常", e);
            }
<script>
// 变换日期
        Date.prototype.toLocaleDateString = function () {
            return this.getFullYear() + "-" + (this.getMonth() + 1) + "-" + this.getDate();
        };
        var date_before = $("#birthday_source").val();
        var unixTimestamp = new Date(date_before * 1000);
        var new_date = unixTimestamp.toLocaleDateString();
        $("#birthday_input").val(new_date);
</script>
 <input id="birthday_input" name="birthday" value="" onchange="save()" style="text-align: right"/>

个人微信公众号,追寻自由,分享生活!
这里写图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值