Date.parse 在 IE 11 中使用 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)) {

我创建了一个虚拟小提琴,它失败了。https://jsfiddle.net/vwwoa32y/

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

日期字符串

表示 RFC2822 或 ISO 8601 日期的字符串(可以使用其他格式,但结果可能是意外的(。

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

解决方案的替代方法是使用 moment.js。它有一个非常强大的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);

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

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

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');
}

最新更新