在Javascript中将包含特定格式日期的字符串解析为Date对象
我正在学习 Javascript 作为一门新语言,我发现一个习惯 JS 如何处理 reg exp 和字符串操作的好方法是将包含日期的字符串解析为 Date 对象。
我有一个 "2005-05-28"
形式的字符串。将其解析为 Date 对象的最佳 Javascript 方法是什么?
I'm learning Javascript as a new language, and I figured a good way to get used to how JS handles reg exp and string manipulation is to parse a string containing a date into a Date object.
I have a string in the form "2005-05-28"
. What is the best Javascript-y way to parse that into a Date object?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
非正则表达式
我不知道“最好”,但你不需要正则表达式:
Live example
使用
String#split
在-
字符上拆分字符串,然后使用接受年、月(从 0 开始)和的Date
构造函数天(从 1 开始)。正则表达式
请注意,如果您确实想要使用正则表达式,您可以:
实例
它使用带有捕获组的正则表达式,通过
String#match
进行匹配,这会返回一个在索引0
处完全匹配的数组,后跟捕获组。但就我的钱而言,正则表达式并没有真正给你带来任何东西。除此之外,
如果您的日期字符串变得更复杂或可能有所不同,我会考虑将问题交给像 DateJS。但如果你的格式是那么常规,那么你就是黄金。
Non-RegExp
I don't know about "best", but you don't need a regex:
Live example
That uses
String#split
to break the string on the-
characters, then theDate
constructor that accepts year, month (starting with 0), and day (starting with 1).RegExp
Mind you, if you really want to use a regexp, you can:
Live example
That uses a regex with capture groups, doing the match via
String#match
, which returns an array with the full match at index0
followed by the capture groups. But for my money, the regex isn't really buying you anything.Beyond
If your date strings get more complicated or may vary, I'd look at farming the problem out to a library like DateJS. But if your format is that regular, you're golden.
该格式对于标准 JS 日期来说是可以接受的。所以你只需要做:
编辑:上面是错误的,TJ 是对的;我被一个懒惰的答案打败了。它甚至在 Firefox 中解析错误,将日期减一。
看到这个问题比我想象的要棘手,我仔细地做了一些测试。 IE(和其他)将接受斜杠而不是破折号(实现优先于规范)。因此,上面的内容将适用于一个简单的replace():
请注意,我还使用 MM/DD/YYYY 成功测试了这一点:
因此斜杠将在所有主要浏览器(包括 IE6)中进行解析。
That format is acceptable for a standard JS date. So you only have to do:
EDIT: The above is wrong and TJ is right; I've been busted with a lazy answer. And it even parses incorrectly in Firefox, subtracting one from the date.
Seeing that this question was trickier than I thought, I ran some tests carefully. IE (and others) will accept a slash instead of a dash (implementation trumps specification). So, the above will work with a simple replace():
Note that I also tested this successfully with MM/DD/YYYY:
So the slashes will parse in all major browsers (including IE6).