Date.parse 使用 NaN 在 IE 11 中失败

Date.parse failing in IE 11 with NaN

当我尝试解析 IE 11 中的日期时,它向我抛出 NaN,但在 chrome/firefox 中我得到以下 timestamp 1494559800000

Date.parse("‎5‎/‎12‎/‎2017 09:00 AM")

以下是我在 IE 11 中失败的情况。是否有任何其他库或方法可以在 IE 11 中修复此问题。

tArray 包含 ["09:00 AM", "05:00 PM"];

var tArray = timings.toUpperCase().split('-');
var timeString1 = currentDate.toLocaleDateString() + " " + tArray[0];
var timeString2 = currentDate.toLocaleDateString() + " " + tArray[1];
var currentTimeString = currentDate.toLocaleDateString() + " " + currentTime.toUpperCase();
//Below is the condition which is failing.
if (Date.parse(timeString1) < Date.parse(currentTimeString) 
                 && Date.parse(currentTimeString) < Date.parse(timeString2)) {

我在失败的地方创建了一个虚拟 fiddle。 https://jsfiddle.net/vwwoa32y/

根据 MDN 文档 Date.parse() 参数:

dateString

A string representing an RFC2822 or ISO 8601 date (other formats may be used, but results may be unexpected).

看起来 Microsoft 根本没有实现您提供的格式。无论如何我都不会使用这种格式,因为它依赖于语言环境(可能只是 dd/mm/yyyy 或者有时也可能适合 mm/dd/yyyy)。

您的解决方案的替代方法是使用 moment.js。它对 creating/parsing/manipulating 日期具有非常强大的 API。我将展示一些有关如何使用它的示例:

//Create an instance with the current date and time
var now = moment();

//Parse the first the first argument using the format specified in the second
var specificTime = moment('5‎/‎12‎/‎2017 09:00 AM', 'DD/MM/YYYY hh:mm a');

//Compares the current date with the one specified
var beforeNow = specificTime.isBefore(now);

它提供的功能更多,可能会帮助您大大简化代码。

编辑: 我使用 moment.js 版本 2.18.1 重写了您的代码,它看起来像这样:

function parseDateCustom(date) {
    return moment(date, 'YYYY-MM-DD hh:mm a');
}

var tArray = ["09:00 AM", "05:00 PM"];
var currentDate = moment().format('YYYY-MM-DD') + ' ';
var timeString1 = parseDateCustom(currentDate + tArray[0]);
var timeString2 = parseDateCustom(currentDate + tArray[1]);
var currentTimeString = parseDateCustom(currentDate + "01:18 pm");

if (timeString1.isBefore(currentTimeString) && currentTimeString.isBefore(timeString2)) {
    console.log('Sucess');
} else {
    console.log('Failed');
}