【问题标题】:In Internet Explorer not able to convert UTC date to local date在 Internet Explorer 中无法将 UTC 日期转换为本地日期
【发布时间】:2017-10-14 03:16:24
【问题描述】:

这是我从后端"2017-05-23T18:30:00" 收到的日期,

这在 Chrome 中运行良好:

  • 电话:new Date('2017-05-23T18:30:00').toString()
  • 结果:"Wed May 24 2017 00:00:00 GMT+0530 (India Standard Time)"

但在 Internet Explorer 上:

  • 电话:new Date('2017-05-23T18:30:00').toString()
  • 结果:"Tue May 23 2017 18:30:00 GMT+0530 (India Standard Time)",

当我进入 Chrome 时,如何从 Internet Explorer 中的 UTC 日期获取本地日期时间?

【问题讨论】:

  • 如果您专门将时间标记为 UTC 是否有帮助:2017-05-23T18:30:00Z
  • @Henry 谢谢,它的工作

标签: javascript date internet-explorer-11 momentjs datejs


【解决方案1】:

您可以使用moment.utc 跨浏览器解析您的输入。然后您可以使用format() 来显示您的时刻对象。如果您需要将时刻对象转换为 JavaScript 日期,您可以使用 toDate() 方法。

如果您想将您的时刻转换为当地时间,请使用local()

更多信息请参见Local vs UTC vs Offset

这是一个现场样本:

var input = '2017-05-23T18:30:00';
var m = moment.utc(input);
console.log(m.format());
console.log(m.toDate().toString());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>

【讨论】:

    【解决方案2】:

    IE 浏览器将采用“mm-dd-yy”格式。如果您以 'yy-mm-dd' 的格式给出,则会导致日期无效。

    使用以下函数将 UTC 转换为 LocalDate。

    function convertUTCDateToLocalDate(utcDate) {
        var formattedDate = utcDate.getMonth()+'-'+utcDate.getDate()+'-'+utcDate.getFullYear();
        var hours = utcDate.getHours();
            var minutes = utcDate.getMinutes();
            var seconds = utcDate.getSeconds()
            var newDate = new Date(formattedDate + ' ' + hours + ':' + minutes+":"+seconds+" UTC");
        return newDate;   
    }
    var localDate = convertUTCDateToLocalDate(yourUTCDate);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-04-07
      • 2021-03-26
      • 2020-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-30
      相关资源
      最近更新 更多