JS 将带T的时间转换为北京时间格式

layui表格经常会遇到时间格式错误问题,以下为格式转换代码:

   { field: 'CreateTime', title: '创建时间', width: '300', templet: function (d) {
                         var date = new Date(Date.parse(d.CreateTime))//时间戳为10位需*1000,时间戳为13位的话不需乘1000
                         var Y = date.getFullYear() + '-';
                         var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
                         var D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';
                         var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
                         var m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
                         var s = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
                         return Y + M + D + h + m + s;
                     } },

以下为UTC格式转换:

            function utc2beijing(utc_datetime) {
                // 转为正常的时间格式 年-月-日 时:分:秒
                var T_pos = utc_datetime.indexOf('T');
                var Z_pos = utc_datetime.indexOf('Z');
                var year_month_day = utc_datetime.substr(0,T_pos);
                var hour_minute_second = utc_datetime.substr(T_pos+1,Z_pos-T_pos-1);
                var new_datetime = year_month_day+" "+hour_minute_second; // 2017-03-31 08:02:06

                // 处理成为时间戳
                timestamp = new Date(Date.parse(new_datetime));
                timestamp = timestamp.getTime();
                timestamp = timestamp/1000;

                // 增加8个小时,北京时间比utc时间多八个时区
                var timestamp = timestamp+8*60*60;

                // 时间戳转为时间
                var beijing_datetime = new Date(parseInt(timestamp) * 1000).toLocaleString().replace(/年|月/g, "-").replace(/日/g, " ");
                return beijing_datetime; // 2017-03-31 16:02:06
            } 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值