参数为IE11的新日期

new Date with param - IE11

本文关键字:日期 新日期 IE11 参数      更新时间:2023-09-26

我有一个函数可以将特定格式的日期字符串转换为JS日期对象:

// param userInputBirthdate is a string with this format `dd.mm.yyyy`
function dateObjFromCHString(userInputBirthdate){
  var paramDate = userInputBirthdate.split('.').reverse().join('-');
  return new Date(paramDate);
}

当用户填写birthDate输入时,通过调用此函数可以成功创建日期对象。

但现在在我的单元测试中,我用这段代码模拟用户给出的字符串(由于个人原因,我必须这样计算日期,所以请不要建议简单地写一个字符串日期常数):

var localDateOptions = {month:'2-digit',year:'numeric',day:'2-digit'};
var today = new Date();
olderDate.setDate(today.getDate()-(25*365));  //25 years ago
olderDate = olderDate.toLocaleDateString('fr-CH',localDateOptions).replace(/'//g,'.');//return something like 23.03.1985

但现在当我用功能转换它时

dateObjFromCHString(olderDate); //returns [date] Invalid Date in IE11

我在IE上得到了一个"Invalid Date"(用IE11边缘模式测试),但在FF、Chrome或Opera上一切都很好。。。有人能告诉我IE的问题是什么吗?

注意:我看到了关于这个问题的其他SO线程,并建议对新的Date参数使用yyyy-mm-dd hh:mm:ss格式,但由于它与new Date('2012-03-11')一起使用,我想知道为什么单元测试代码不起作用。

我在这个问题的帮助下发现了这个问题:IE11 中的ToLocaleDateString()更改

如果您分别记录tolocalDateString结果的每个字符,您将看到在记录完整结果时没有显示未显示的字符。

例如:

var str=(new Date).toLocaleDateString();
for(var i=0;i<str.length;i++)
console.log(i,str.charCodeAt(i),str.charAt(i))

会用IE11:输出这样的东西

0  8206 ‎
1  49    1
2  57    9
3  8206
‎4  46    .
5  8206 ‎
6  48    0
7  53    5
8  8206 ‎
9  46    .
10 8206 ‎
11 50    2
12 48    0
13 49    1
14 53    5

正如您所看到的,有5个不可见的字符(charcode=8206)将破坏我从toLocaleDateString结果到日期的转换。

我使用momentjs库来处理单元测试中的所有日期函数,从而解决了这个问题。