Regular Expression for Date and Time Strings

by Yang Yang on September 29, 2010

Often we need the users to enter a valid string of date or time in the form. But how do you validate the strings with regular expressions? In PHP, you can use these functions and regular expressions.

RegExp and function to validate against date string:

// Default: YYYY-MM-DD
function isDate($subject, $separator = '-') {
	return preg_match('@^\d{4}'.$separator.'(0[1-9]|1[0-2])'.$separator.'(0[1-9]|1[0-9]|2[0-9]|3[0-1])$@', $subject);
}

RegExp and function to validate against time string:

// Default: HH:MM:SS
function isTime($subject, $separator = ':') {
	return preg_match('@^(0[1-9]|1[0-9]|2[0-4])'.$separator.'(0[1-9]|[1-5][0-9])'.$separator.'(0[1-9]|[1-5][0-9])$@', $subject);
}

If you need to validate against a different format, just change the $separator.

Now that you have the functions to validate date and time, you can combine them to verify date time strings such as 2016-04-30 18:19:05:

function isDateTime($subject) {
	$subject_array = explode(' ', $subject);
	if (count($subject_array) == 2) {
		return isDate($subject_array[0]) && :isTime($subject_array[1]) || $subject == '0000-00-00 00:00:00';
	}
	return false;
}

At Form Kid, these are functions I use for fields that need validation of the date and time.

Mantish December 22, 2012 at 12:33 am

Hi, thanks for the functions!

I think there’s an error in isTime()
The regular expression should be ‘@^(0[0-9]|1[0-9]|2[0-4])’.$separator.'(0[0-9]|[1-5][0-9])’.$separator.'(0[0-9]|[1-5][0-9])$@’

Comments on this entry are closed.

Previous post:

Next post: