【问题标题】:Date.parse failing in IE 11 with NaNDate.parse 在 IE 11 中使用 NaN 失败
【发布时间】:2017-05-12 17:58:21
【问题描述】:

当我尝试解析 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/

【问题讨论】:

  • 你显示的字符串中包含一堆不可打印的字符(Date.parse("&lt;00e2&gt;&lt;0080&gt;&lt;008e&gt;5...),你确定不是这个引起的吗?
  • @robertklep:我在哪里展示?
  • 嗯,它们是不可打印的,所以它们没有显示,但它们在那里。在这两种情况下,将该行代码剪切并粘贴到 Node 或 Chrome 控制台并执行它都会返回 NaN
  • @robertklep:你的意思是这一行,Date.parse("‎5‎/‎12‎/‎2017 09:00 AM"),我正在尝试...
  • 是的,那行。字符是&amp;lrm;

标签: javascript internet-explorer-11


【解决方案1】:

根据MDN docs for Date.parse() 参数:

日期字符串

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

看起来微软根本没有实现您提供的格式。无论如何我都不会使用这种格式,因为它取决于语言环境(可能只是 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);

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

编辑: 我使用 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');
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-19
    • 2013-08-31
    • 2015-12-27
    • 2019-03-29
    • 2012-07-16
    • 1970-01-01
    • 1970-01-01
    • 2016-08-13
    相关资源
    最近更新 更多