javascript 日期时间格式正则表达式YYYY/MM/DD hh:mm:ss

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13682041/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 19:27:21  来源:igfitidea点击:

DateTime format Regular expression YYYY/MM/DD hh:mm:ss

javascriptregexdatetime

提问by user1629434

Can someone write a regular expression to test this date format 2012/11/14 14:28:12?

有人可以写一个正则表达式来测试这种日期格式2012/11/14 14:28:12吗?

I already have a regular expression for the date part:

我已经有了日期部分的正则表达式:

/^\d{4}\/\d{2}\/\d{2}$/

How can I add to this to test for the presence of a time?

我如何添加到这个来测试时间的存在?

回答by David Hellsing

I‘d use the Dateconstructor instead to test a date in that format:

我会使用Date构造函数来测试该格式的日期:

var isValid = !!new Date('2012/11/14 14:28:12').getTime();

Demo: http://jsfiddle.net/rwCeA/

演示:http: //jsfiddle.net/rwCeA/

Works in all my test browsers (safari/chrome/firefox/ie7+). The Date constructor takes many date variants, but you can combine this with a regexp to force a certain format.

适用于我所有的测试浏览器(safari/chrome/firefox/ie7+)。Date 构造函数采用许多日期变体,但您可以将其与正则表达式结合使用以强制使用某种格式。

回答by HBP

This fiddle http://jsfiddle.net/jstoolsmith/Db3JM/I wrote recently is a more sophisticated piece of code, the relevant regular expression is :

我最近写的这个小提琴http://jsfiddle.net/jstoolsmith/Db3JM/是一段更复杂的代码,相关的正则表达式是:

/(?:(\d{4})([\-\/.])([0-3]?\d)([0-3]?\d)|([0-3]?\d)([\-\/.])([0-3]?\d)(\d{4}))(?:\s+([012]?\d)([:hap])([0-5]\d))?/i