Sha*_*ane 6 javascript internet-explorer-11
当我尝试解析中的日期时IE 11,它抛出NaN,但在chrome / firefox中,我得到了以下内容timestamp 1494559800000
Date.parse("?5?/?12?/?2017 09:00 AM")
Run Code Online (Sandbox Code Playgroud)
以下是在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)) {
Run Code Online (Sandbox Code Playgroud)
我创建了一个失败的虚拟小提琴。 https://jsfiddle.net/vwwoa32y/
根据MDN文档中的Date.parse()参数:
dateString
表示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);
Run Code Online (Sandbox Code Playgroud)
它提供了更多功能,可能会极大地帮助您简化代码。
编辑:
我使用moment.js2.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');
}
Run Code Online (Sandbox Code Playgroud)