手机中使用new Date()格式化某个时间时,时间朝后加了8小时

clipboard.png

<body>
  <p>原始日期:<br/>2017-10-19T14:51:52</p>
  <p id="test"></p>
  <p id="test2"></p>
  <p id="test3"></p>
  <script>
  Date.prototype.Format = function(c) {
    var o = {
      "M+": this.getMonth() + 1,
      "d+": this.getDate(),
      "h+": this.getHours(),
      "m+": this.getMinutes(),
      "s+": this.getSeconds(),
      "q+": Math.floor((this.getMonth() + 3) / 3),
      S: this.getMilliseconds()
    };
    /(y+)/.test(c) && (c = c.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length)));
    for (var a in o) new RegExp("(" + a + ")").test(c) && (c = c.replace(RegExp.$1, 1 == RegExp.$1.length ? o[a] : ("00" + o[a]).substr(("" + o[a]).length)));
    return c
  };
  var t = new Date('2017-10-19T14:51:52');
  var getDate = function(d) {
    return "number" != typeof d && (d = 1e3 * parseInt(d)), d ? new Date(d).Format("yyyy-MM-dd hh:mm:ss") : "0000-00-00 00:00:00"
  }
  var t2 = getDate(t.getTime());

  document.getElementById('test').innerHTML = '时间格式化t:<br/>'+t;
  document.getElementById('test2').innerHTML = '时间格式化t2:<br/>'+t2;
  document.getElementById('test3').innerHTML = '时间-当前系统时间:<br/>'+new Date();
  </script>
</body>
阅读 13.7k
5 个回答

原因不太清楚,从结果看new Date()的时候把传入的时间当成是世界标准时间了,可以明确的给时间后面加上时区:new Date('2017-10-19T14:51:52+0800');
补充
在safari浏览器,new Date() 中传入的参数的参数中不能识别‘-’,‘T’,所以需要转化一下,兼容性函数如下:

function fixDate(strTime) {
    if (!strTime) {
      return '';
    }
    var tempDate = new Date(strTime+'+0800');
    if(tempDate=='Invalid Date'){
        strTime = strTime.replace(/T/g,' ');
        strTime = strTime.replace(/-/g,'/');
        tempDate=new Date(strTime+'+0800');
    }
    tempDate.toLocaleDateString();
    return tempDate;
  }

安卓会把这个带T字母的时间看做UTC时间格式,(包括ios打包后也会相差8个小时)与北京时间相差8个小时。你要将UTC时间转化为北京时间然后进行格式化。GMT +0800 已经是加了8个小时的了。或者你直接把T替换掉,然后格式化。

ios中要把毫秒也去掉 不然也没有效果 贴上根据1楼改的代码

if (!strTime) {
    return '';
}
var myDate = new Date(strTime + '+0800');
if (myDate == 'Invalid Date') {
    strTime = strTime.replace(/T/g, ' ');
    strTime = strTime.replace(/-/g, '/');
    strTime = strTime.replace(/\.\d+/, ' ');
    myDate = new Date(strTime + '+0800');       
}   

new Date('2017-10-16')---返回2017-10-16相对于8时的时间
new Date('2017/10/16') ---返回2017/10/16相对于0时的时间

你先变成时间戳去转换

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题