0

Can someone write a regular expression to test this date format 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?

Paul D. Waite
  • 96,640
  • 56
  • 199
  • 270
user1629434
  • 35
  • 1
  • 1
  • 6

2 Answers2

5

Iā€˜d use the Date constructor instead to test a date in that format:

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

Demo: 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.

David Hellsing
  • 106,495
  • 44
  • 176
  • 212
4

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

/(?:(\d{4})([\-\/.])([0-3]?\d)\2([0-3]?\d)|([0-3]?\d)([\-\/.])([0-3]?\d)\6(\d{4}))(?:\s+([012]?\d)([:hap])([0-5]\d))?/i
HBP
  • 15,685
  • 6
  • 28
  • 34