I need a regular expression to validate a timestamp of the format, using Javascript:
YYYY/MM/DD HH:MI:SS
I trie
Here is how I build up a regex matching exactly SQL Timestamp yyyy-mm-dd hh:mm:ss
in the range
[1970-01-01 00:00:00
, 2037-12-31 23:59:59
]
$leapYear = "(19[79][26]|198[048]|20[02][048]|20[13][26])";
$leapDate = "$leapYear-02-29";
$regularYear = "(19[789][0-9]|20[012][0-9]|203[0-7])";
$regularFebruaryDate = "02-([01][1-9]|2[0-8])";
$month31Date = "(0[13578]|10|12)-([012][1-9]|3[01])";
$month30Date = "(0[469]|11)-([012][1-9]|30)";
$regularDate = "$regularYear-($regularFebruaryDate|$month30Date|$month31Date)";
$hours = "(2[0-3]|[01][0-9])";
$minutes = "[0-5][0-9]";
$seconds = "[0-5][0-9]";
$sqlTimestamp = "($leapDate|$regularDate) $hours:$minutes:$seconds";
Note: I avoided the year 2038 to have one less edge-case. The max possible SQL timestamp is 2038-01-19 03:14:07
.
Regular-Expressions.info is a nice source of information about RegEx, it also has a good tutorial.
I would recommend to use Datejs for this. Parsing the date yourself is not necessary and a Regex is not enough to validate a timestamp. With datejs you could parse the string in a date and you'll get null if its invalid:
Date.parse("2009/06/29 13:30:10", "yyyy/MM/dd HH:mm:ss");
If you just want to validate the syntax, here is the POSIX regex:
[0-9]{1,4}/[0-9]{1,2}/[0-9]{1,2} [0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2}
But if you want to check the semantics, I would process the string using your language of choice, there are too many cases you cannot cover with regular expressions (like leap years/seconds, daylight savings, etc)
perl style: [12]\d{3}/[01]\d/[0-3]\d [0-2]\d(?::[0-5]\d){2}
This is the regex you are looking for:
[0-9]{4}/(0[1-9]|1[0-2])/(0[1-9]|[1-2][0-9]|3[0-1]) (2[0-3]|[01][0-9]):[0-5][0-9]:[0-5][0-9]