在JavaScript中解析字符串到日期
如何在 JavaScript 中将字符串转换为 Date 对象?
var st = "date in some format"
var dt = new Date();
var dt_st = // st in Date format, same as dt.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(30)
字符串解析的最佳字符串格式是日期 ISO 格式以及 JavaScript Date 对象构造函数。
ISO 格式示例:
YYYY-MM-DD
或YYYY-MM-DDTHH:MM:SS
。但是等等!仅使用“ISO 格式”本身并不能可靠地工作。字符串有时被解析为 UTC,有时被解析为本地时间(基于浏览器供应商和版本)。最佳实践应始终是将日期存储为 UTC 并按 UTC 进行计算。
要将日期解析为 UTC,请附加 Z - 例如:
new Date('2011-04-11T10:20:30Z')
。要显示 UTC 日期,请使用
.toUTCString()
,要显示用户当地时间的日期,请使用
.toString()
。有关 MDN | 的更多信息日期和此答案。
为了兼容旧版 Internet Explorer(小于 9 的 IE 版本不支持日期构造函数中的 ISO 格式),您应该将日期时间字符串表示形式拆分为其各个部分,然后您可以使用日期时间部分来使用构造函数,例如:
new Date('2011 '、'04' - 1、'11'、'11'、'51'、'00')
。请注意,月份数必须少 1。替代方法 - 使用适当的库:
您还可以利用库 Moment.js允许解析具有指定时区的日期。
The best string format for string parsing is the date ISO format together with the JavaScript Date object constructor.
Examples of ISO format:
YYYY-MM-DD
orYYYY-MM-DDTHH:MM:SS
.But wait! Just using the "ISO format" doesn't work reliably by itself. String are sometimes parsed as UTC and sometimes as localtime (based on browser vendor and version). The best practice should always be to store dates as UTC and make computations as UTC.
To parse a date as UTC, append a Z - e.g.:
new Date('2011-04-11T10:20:30Z')
.To display a date in UTC, use
.toUTCString()
,to display a date in user's local time, use
.toString()
.More info on MDN | Date and this answer.
For old Internet Explorer compatibility (IE versions less than 9 do not support ISO format in Date constructor), you should split datetime string representation to it's parts and then you can use constructor using datetime parts, e.g.:
new Date('2011', '04' - 1, '11', '11', '51', '00')
. Note that the number of the month must be 1 less.Alternate method - use an appropriate library:
You can also take advantage of the library Moment.js that allows parsing date with the specified time zone.
不幸的是我发现
返回“2014 年 4 月 2 日星期三”。我知道这听起来很疯狂,但它发生在某些用户身上。
防弹解决方案如下:
Unfortunately I found out that
returns "Wed Apr 02 2014". I know it sounds crazy, but it happens for some users.
The bulletproof solution is the following:
输出将是:
And the output will be:
更新:Moment 现已弃用,一个不错的替代方案目前是 datefns https://date-fns.org/
moment.js (http://momentjs.com/) 是一个完整且良好的使用日期包,支持 ISO 8601 字符串。
您可以添加字符串日期和格式。
您可以检查日期是否有效。
一些显示示例
请参阅文档
http://momentjs.com/docs/#/parsing/string-format/
Update: Moment is now deprecated, A good alternative for moment is datefns https://date-fns.org/
moment.js (http://momentjs.com/) is a complete and good package for use dates and supports ISO 8601 strings.
You could add a string date and format.
And you could check if a date is valid.
Some display examples
See documentation
http://momentjs.com/docs/#/parsing/string-format/
将其作为参数传递给 Date():
您可以使用以下方式访问日期、月份、年份:
dt.getMonth()
。Pass it as an argument to Date():
You can access the date, month, year using, for example:
dt.getMonth()
.只是
new Date(st);
假设它是正确格式。
Just
new Date(st);
Assuming that it's the proper format.
对于那些正在寻找小型智能解决方案的人:
示例:
For those who are looking for a tiny and smart solution:
Example:
如果您可以使用出色的 luxon 库库您可以轻松地使用EG来解析您的日期
,并且可以访问您JS日期对象通过
使用的旧答案
If you can use the terrific luxon library you can easily parse your date using e.g.
and can access the JS date object via
The old answer used MomentJS
new Date(2000, 10, 1)
将为您提供“Wed Nov 01 2000 00:00:00 GMT+0100 (CET)”请注意,月份 0 为您提供一月
new Date(2000, 10, 1)
will give you "Wed Nov 01 2000 00:00:00 GMT+0100 (CET)"See that 0 for month gives you January
在我看来,这是最好,更简单的解决方案:
只需加入日期字符串(使用 iso格式)最后,“ t00:00:00”最后使用 JavaScript Date()构造函数,如下所示。
仅有关上述解决方案的一些细节(但可选的阅读):
重要的是要注意,上面的示例将为您提供以下示例的完全相同的返回,这是该问题中第二个选票的答案:
主要区别是,此处提供的第一个示例比第二个示例更简单,甚至更多的错误证明一个(至少在我看来,如下所述)。
因为如果您调用仅使用ISO格式的一个日期弦乐参数(第一个示例),它不接受高于其逻辑限制的值(因此,如果您给出13个月份或每天32个,则会获得无效的日期)。
但是,当您将同一构造函数与多个date-arguments(第二个示例)(第二个示例)时,逻辑限制将被调整为相邻值,并且您将不会得到无效的日期错误(因此,如果您给出13个月份,它将调整为1,而不是给予。您的日期无效)。
或替代方案(和第三)解决方案都可以混合在一起,使用第一个示例仅验证日期弦,如果它是有效的,请使用第二个示例(因此,您避免了可能的浏览器不一致,同时避免第二个示例的逻辑限制的参数许可)。
像这样(也接受部分日期):
第四个替代方案(和最后的建议)将是使用适当的第三库(例如或 date-fns )
参考:
That's the best and simpler solution in my view:
Just concatenate your date string (using ISO format) with "T00:00:00" in the end and use the JavaScript Date() constructor, like the example below.
And just a few details about the solution above (but optional reading):
Important to note that the example above will give you exactly the same return to this example below, that is the second most voted answer in this question:
The main difference is that the first example provided here is simpler and even more error proof than the second one (at least in my view, as explained below).
Because if you call the JavaScript Date() constructor date with just one date-string argument in ISO format (first example), it doesn't accept values above its logical limit (so, if you give 13 as month or 32 as day, you get Invalid Date).
But when you use the same constructor with multiple date-arguments (second example), parameters above it logical limit will be adjusted to the adjacent value and you won't get Invalid Date Error (so, if you give 13 as month, it will adjust to 1, instead of give you an Invalid Date).
Or an alternative (and third) solution would be mix both, use the first example just to validate the date-string and if it is valid use the second example (so you avoid possible browsers inconsistences of the first example and at the same time avoid the permission of parameters above it logical limit of the second example).
Like so (accepting partial dates as well):
And a fourth alternative (and last suggestion) would be to use an appropriate third library (like moment or date-fns)
References:
如果您想从格式转换为“ DD/mm/yyyy”。这是一个示例:
此解决方案在IE版本中起作用,小于9。
If you want to convert from the format "dd/MM/yyyy". Here is an example:
This solution works in IE versions less than 9.
时间戳应该转换为数字
Timestamps should be casted to a Number
date.parse
几乎可以为您带来想要的东西。它在am
/pm
零件上窒息,但是有些黑客可以使它起作用:Date.parse
almost gets you what you want. It chokes on theam
/pm
part, but with some hacking you can get it to work:今天的性能
(2020.05.08)我执行选择解决方案的测试 - 对于两种情况:输入日期为ISO8601字符串(AD,BD,CD,CD,DD,ED),并且输入日期为 timestamp (at,ct,dt)。 Solutions BD,CD,CT不返回JS日期对象作为结果,但我添加它们是因为它们可以有用,但我不将它们与有效解决方案进行比较。该结果对于大规模日期解析可能很有用。
结论
新日期
(AD)的速度比Moment.JS(DD)快50-100x,用于ISO日期和时间戳新日期
(AD)为〜10X比parsedate
(ed)date.parse.parse
(bd)更快,如果WEE需要从所有浏览器上从ISO日期获得时间戳“ rel =“ noreferrer
i.sstatic.net/yjdwq.png 在Chrome 81.0,Safari 13.1,Firefox 75.0上对MacOS高塞拉10.13.6进行测试。解决方案
parsedate
(ed)使用new Date(0)
并手动设置UTC日期组件。Chrome
Performance
Today (2020.05.08) I perform tests for chosen solutions - for two cases: input date is ISO8601 string (Ad,Bd,Cd,Dd,Ed) and input date is timestamp (At, Ct, Dt). Solutions Bd,Cd,Ct not return js Date object as results, but I add them because they can be useful but I not compare them with valid solutions. This results can be useful for massive date parsing.
Conclusions
new Date
(Ad) is 50-100x faster than moment.js (Dd) for all browsers for ISO date and timestampnew Date
(Ad) is ~10x faster thanparseDate
(Ed)Date.parse
(Bd) is fastest if wee need to get timestamp from ISO date on all browsersDetails
I perform test on MacOs High Sierra 10.13.6 on Chrome 81.0, Safari 13.1, Firefox 75.0. Solution
parseDate
(Ed) usenew Date(0)
and manually set UTC date components.Results for chrome
转换为格式pt-br:
我希望帮助某人!!!
Convert to format pt-BR:
I hope help somebody!!!
我为此创建了一个小提琴,您可以在任何日期字符串上使用 toDate() 函数并提供日期格式。这将返回一个 Date 对象。
https://jsfiddle.net/Sushil231088/q56yd0rp/
I have created a fiddle for this, you can use toDate() function on any date string and provide the date format. This will return you a Date object.
https://jsfiddle.net/Sushil231088/q56yd0rp/
对于js中的converting字符串,我使用
http://momentjs.com/
For сonverting string to date in js i use
http://momentjs.com/
我使此功能将任何日期对象转换为UTC日期对象。
I made this function to convert any Date object to a UTC Date object.
您可以使用正则表达式解析字符串以详细说明时间,然后创建日期或任何返回格式,例如:
You can using regex to parse string to detail time then create date or any return format like :
您可以尝试一下:
You Can try this:
这个答案基于 Kassem 的答案,但它也处理两位数的年份。我提交了对卡西姆答案的编辑,但如果未获得批准,我也会将其作为单独的答案提交。
This answer is based on Kassem's answer but it also handles two-digit years. I submitted an edit to Kassem's answer, but in case it wasn't approved, I'm also submitting this as a separate answer.
或者
“01-01-1970”格式的日期字符串在 FireFox 中不起作用,因此最好在日期格式字符串中使用“/”而不是“-”。
or
date string in format '01-01-1970' will not work in FireFox, So better use "/" instead of "-" in date format string.
还有另一种方法可以做到这一点:
Yet another way to do it:
如果您需要在转换为日期格式之前检查字符串的内容:
If you need to check the contents of the string before converting to Date format:
我已经创建了ParseDateTime函数以将字符串转换为日期对象,并且它在所有浏览器(包括IE浏览器)中工作,检查是否需要,参考
https://github.com/umesh-markande/解析 - 弦乐到日期 - 全螺旋体
I have created parseDateTime function to convert the string to date object and it is working in all browser (including IE browser), check if anyone required, reference
https://github.com/Umesh-Markande/Parse-String-to-Date-in-all-browser
ISO 8601 式的日期字符串虽然非常优秀,但仍未得到广泛支持。
这是一个很好的资源,可以帮助您确定应该使用哪种日期字符串格式:
http://dygraphs.com/date- format.html
是的,这意味着您的日期字符串可以像
"2014/10/13 23:57:52"
一样简单而不是
“2014-10-13 23:57:52”
ISO 8601-esque datestrings, as excellent as the standard is, are still not widely supported.
This is a great resource to figure out which datestring format you should use:
http://dygraphs.com/date-formats.html
Yes, that means that your datestring could be as simple as as opposed to
"2014/10/13 23:57:52"
instead of
"2014-10-13 23:57:52"
作为此处解释的内容的插件,您可以使用
new Date()
创建日期,并使用非常有用的toLocaleDateString() functionAn example:
console.log(new Date('1970-01- 01')。tolocaledateString('es-es'))// - >这将输出'1/1/1970'
As an addon to what has been explained here, you can create your Date with
new Date()
and format it with the incredibly useful toLocaleDateString() functionAn example:
console.log(new Date('1970-01-01').toLocaleDateString('es-ES')) // --> This will output '1/1/1970'
使用这段代码:(我的问题已经用这段代码解决了)
}
use this code : (my problem was solved with this code)
}