如何在chrome浏览器以及firefox浏览器中验证日期

Ash*_*ani 3 javascript google-chrome date cross-browser

在chrome中我试图检查日期是否是有效日期.

有一个变量:

var d = new Date('9/'); // Not a correct format
Run Code Online (Sandbox Code Playgroud)

在Chrome中

console.log(new Date('9/')); // Output: Sat Sep 01 2001 00:00:00 GMT+0530 (India Standard Time) Which is wrong as I am providing wrong date.
Run Code Online (Sandbox Code Playgroud)

在Firefox中

console.log(new Date('9/')); // Output: Invalid Date
Run Code Online (Sandbox Code Playgroud)

还使用firefox中的date.toLocaleString()输出06 May 2007 00:00:00

在铬中它是1/9/2001;

所以我的问题是如何在chrome中验证日期并保持代码不受这些差异的影响.如果需要更多细节请写评论.

Spu*_*ley 5

正如您所发现的,Javascript Date API可能会在浏览器之间产生一些混合的结果.

我建议的最佳选择是使用可用于此的第三方库之一.有两个我可以推荐-无论是Moment.js或Date.js.

这两个lib都有更好的验证和解析,并且比内置的Date类更加一致的跨浏览器.