在 JavaScript 中将字符串解析为日期
如何在 JavaScript 中将字符串转换为 Date 对象?
var st = "date in some format"
var dt = new Date();
var dt_st = // st in Date format, same as dt.
How can I convert a string to a Date object in JavaScript?
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.
如果您可以使用很棒的 luxon 库,您可以使用例如轻松解析您的日期
并可以访问JS 日期对象通过
旧答案使用 MomentJS
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
对于那些正在寻找小型智能解决方案的人:
示例:
For those who are looking for a tiny and smart solution:
Example:
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() 构造函数,如下例所示。
关于上述解决方案的一些细节(但可选阅读):
重要的是要注意,上面的示例将为您提供与下面的示例完全相同的返回值,这是该问题中投票第二多的答案:
主要区别在于,此处提供的第一个示例比第二个示例更简单,甚至更防错一个(至少在我看来,如下所述)。
因为如果您调用 JavaScript Date() 构造函数< /a> date 只有一个 ISO 格式的日期字符串参数(第一个示例),它不接受高于其逻辑限制的值(因此,如果您将 13 作为月份或 32 作为日期,则会得到无效日期)。
但是,当您使用具有多个日期参数的相同构造函数(第二个示例)时,高于逻辑限制的参数将调整为相邻值 并且您不会收到无效日期错误(因此,如果您给出 13 作为月份,它将调整为 1,而不是给出您的日期无效)。
或者替代(和第三)解决方案将两者混合,使用第一个示例只是为了验证日期字符串,如果它有效,则使用第二个示例(这样您就可以避免第一个示例的浏览器可能不一致,同时避免高于第二个示例的逻辑限制的参数的权限)。
像这样(也接受部分日期):
第四个替代方案(也是最后一个建议)是使用适当的第三个库(例如 moment 或 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、Dd、Ed),输入日期为 时间戳(At、Ct、Dt)。解决方案 Bd、Cd、Ct 不会返回 js Date 对象作为结果,但我添加它们是因为它们可能有用,但我没有将它们与有效的解决方案进行比较。此结果对于大规模日期解析非常有用。
结论
new Date
(Ad) 比 moment.js (Dd) 快 50-100 倍new Date
(Ad) 大约是 10 倍比parseDate
更快 (Ed)Date.parse
(Bd) 是最快的详细信息
I在 Chrome 81.0、Safari 13.1、Firefox 75.0 上的 MacOs High Sierra 10.13.6 上执行测试。解决方案
parseDate
(编辑)使用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 中将字符串转换为日期,我使用
http://momentjs.com/
For сonverting string to date in js i use
http://momentjs.com/
我创建了这个函数来将任何 Date 对象转换为 UTC Date 对象。
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() 函数示例:
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)
}