将日期格式化为新日期在 IE 中不起作用

Formatting date to new date not working in IE

我目前有以下代码:

lastLoginDate = "\/Date(1499994230140+0800)\/";
lastLoginDate = moment(lastLoginDate).format("YYYY-MM-DD hh:mm:ss UTC");
lastLoginDate = new Date(lastLoginDate);

这适用于 chrome。但是当 运行 在 IE 中时,新日期 returns 无效日期。我如何在 IE 中实现相同的输出?

根本不需要格式化然后再解析日期。只需使用 toDate():

lastLoginDate = moment(lastLoginDate).toDate();

如果这不起作用,那么您的 lastLoginDate 格式有误。您可以阅读有关有效格式的更多信息 here

您可以使用正则表达式将字符串拆分为 Unix 时间和时区偏移量。

下面的代码很容易理解。

const dateRegex = /^\/Date\((\d+)([-+]\d{4})\)\/$/;
const dateFormat = 'YYYY-MM-DD hh:mm:ss Z';
  
let lastLoginDate = "\/Date(1499994230140+0800)\/";
console.log(parseTimestamp(lastLoginDate));

function parseTimestamp(timestamp) { 
  var groups = dateRegex.exec(timestamp);
  var unixTime = Math.floor(parseInt(groups[1], 10) / 1000);
  var timezoneOffset = groups[2];

  return moment.unix(unixTime).utcOffset(timezoneOffset).format(dateFormat);
}

// Output: 2017-07-14 09:03:50 +08:00
.as-console-wrapper { top: 0; max-height: 100% !important; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>

通过将格式更改为 yyyy/mm/dd 而不是 yyyy-mm-dd

解决了我的问题
moment(lastLoginDate).format("YYYY/MM/DD hh:mm:ss UTC");