Javascript:`new Date(dateString)`vs`new Date(year,month,day)`之间的区别` [英] Javascript: Difference between `new Date(dateString)` vs `new Date(year, month, day)`

查看:169
本文介绍了Javascript:`new Date(dateString)`vs`new Date(year,month,day)`之间的区别`的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

参考这个问题所接受的答案如何获取JavaScript中两个日期之间的天数?我看到,在函数 parseDate 中:

  function parseDate(str) {
var mdy = str.split('/')
return new Date(mdy [2],mdy [0] -1,mdy [1]);
}

他这样做:

  var mdy = str.split('/')
return new Date(mdy [2],mdy [0] -1,mdy [1]);

ie。将传递的日期分割为月,日,年,然后将其传递到日期,如新日期(年,月,日),而他可以简单地做新的Date(str),它会返回相同的结果(不是吗?任何人都可以解释两种方式的区别?



更新:测试结果:



$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ b $ )// Sat Jan 01 2000 00:00:00 GMT + 0500(巴基斯坦标准时间)
console.log(new Date(mdy [2],mdy [0] -1,mdy [1])); // Sat Jan 01 2000 00:00:00 GMT + 0500(巴基斯坦标准时间)


解决方案

不,他们是不一样的(即使假设你会在一个月后减去:他正在做 mdy [0] - 1 )因为新日期(str)是必需的(按照标准,请参阅§15.9.4.2)仅接受特定格式的日期ISO 8601( YYYY-MM-DDTHH:mm:ss.sssZ ,另见这篇文章,我不会在这里重复):


如果String不符合该格式[ISO 8601],则函数可能会下降回到任何实现特定的启发式或实现特定的日期格式。


请注意(正如Royi在评论),也支持RFC 2822 (根据 MDN ),但在 JavaScript规范,Internet Explorer不正式支持它(请参阅 MSDN ,它可以解析相似的东西,但不一样)。



在代码中,他们使用特定的语言环境规则( MM / DD / YYYY 解析,我想 en-US locale,但不仅仅是一个)。老实说,我甚至不会使用该代码进行解析(因为是的,实际上它将被破坏为不同的区域设置:即使用于分割的分隔符也不是区域设置安全)。让我举个例子说明一下:




  • 您正在使用正确的配置日期时间选择器(或< input type =date/> 在支持的情况下,您将根据您的区域设置输入日期。例如在意大利(但通常在欧洲),我们写了 DD / MM / YYYY

  • 现在我们假设用户选择了 2014年12月21日(格式为 21/12/2014 根据他的地区)。

  • 使用字符串拆分代码将失败(因为它会选择21作为月份号,显然这是无效的)。甚至更糟糕的是,这样的错误甚至可能不被忽视(例如,如果用户选择 1/2/2014 代码将认为它是 1月2日但用户选择 1月1日)。你想让它更复杂吗?即使 new Date(str)可能会失败,因为它依赖于浏览器(并且您不能真正地相信启发式可移植和安全) li>


如果你问自己那么为什么他们使用这样的代码?我会说,他们使用快速的解决方法来支持使用en-US语言环境的日期(可能是因为他们使用的浏览器不支持他们与启发式猜测),但这不是您应该重复使用的。 p>

解决方案?不要手工解析日期(除非你真的很深刻地知道你在做什么),使用一个好的图书馆(例如时刻。 js ),因为您可能会对日期格式化做出最大的假设是... 错误


Referencing to the accepted answer on this question How do I get the number of days between two dates in JavaScript?. I see, in the function parseDate:

function parseDate(str) {
    var mdy = str.split('/')
    return new Date(mdy[2], mdy[0]-1, mdy[1]);
}

He is doing this:

var mdy = str.split('/')
return new Date(mdy[2], mdy[0]-1, mdy[1]);

i.e. splitting the passed date into month, day and year and then passing it on to Date like new Date(year, month, day) while he could simply do new Date(str) and it would have returned the same result (Wouldn't it?). Can anyone please explain the difference between both the ways?

Update: Test results:

var str = '1/1/2000'
var mdy = str.split('/')
console.log( new Date(str) ) // Sat Jan 01 2000 00:00:00 GMT+0500 (Pakistan Standard Time)
console.log( new Date(mdy[2], mdy[0]-1, mdy[1]) ); // Sat Jan 01 2000 00:00:00 GMT+0500 (Pakistan Standard Time)

解决方案

No, they're not the same (even assuming you'll subtract one month later: he's doing mdy[0] - 1) because new Date(str) is required (by standard, see §15.9.4.2) to accept only date in a specific format ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ, see also this post, I won't repeat myself here):

If the String does not conform to that format [ISO 8601] the function may fall back to any implementation-specific heuristics or implementation-specific date formats.

Please note (as pointed out by Royi in comments) that also RFC 2822 should be supported (according to MDN) but it's not mentioned in JavaScript specifications and Internet Explorer doesn't officially support it (see MSDN, it can parse something similar but it's not the same).

In that code they're parsing using a specific locale rules (MM/DD/YYYY, I suppose en-US locale but it's not only one). To be honest I wouldn't even use that code for parsing (because yes, actually it'll be broken for a different locale: even separator used for splitting is not "locale safe"). Let me explain with an example:

  • You're using a proper configured date time picker (or <input type="date"/> when supported) you'll enter date according to your locale. For example in Italy (but in general in Europe) we write DD/MM/YYYY.
  • Now let's imagine that user picked 21 December 2014 (formatted as 21/12/2014 according to his locale).
  • With string splitting that code will fail (because it'll pick 21 as month number, obviously it's not valid). Even worse than that such errors may even go unnoticed (for example if user picks 1/2/2014 code will "think" it's 2nd Jan but user picked 1st Feb). Do you want to make it more complicate? Even new Date(str) may fail because it's browser dependent (and you can't really trust heuristic to be portable and safe).

If you're asking yourself "Then why they used such code?" I'd say that they used a quick workaround to support dates using en-US locale (probably because browser they used didn't support them with heuristic guess) but it's not something you should reuse.

Solution? Do not ever parse date by hand (unless you really and deep know what you're doing), use a good library (for example moment.js) for that because most assumption you may do about date formatting are...wrong.

这篇关于Javascript:`new Date(dateString)`vs`new Date(year,month,day)`之间的区别`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆