Parse a date by a specific date format in PHP

In the name of code readability and functionality, if you want to parse a date of a certain format you should do it in a way so that other programmers that look at your code can tell what you were doing.

Here is a way as of PHP >= 5.3.0 to parse a string to a Unix style time stamp in PHP, instead of using strtotime which has some tricky requirements that are not made clear in the documentation. This way we can explicitly define the format and how the parser interprets it for the reader of the code, instead of relying on implicit functionality of strtotime and having to make sure the format is what strtotime requires.


//Parse a string to a date of the following format:
//d-m-Y H:i:s
//which is of the format:
//d = day(01-31)
//-
//m = month(01-12)
//-
//Y = year(2000-2099)
//
//H = hour(00-24)
//:
//i = minutes(00-59)
//:
//s = seconds(00-59)

//example:
$server_date_str='06-10-2013 16:00:09';

//PARSE TIME TO UNIX TIME STAMP:
//you may find the below redundant. We are using
//createFromFormat so that we can see we are
//explicitly parsing the format d-m-Y H:m:s
//instead of strtotime whose requirements are elusive
//here we know exactly what format is being parsed
//by looking at the code DateTime::createFromFormat

try {

//get DateTime object
$server_date_time = DateTime::createFromFormat
(
'd-m-Y H:i:s',
$server_date_str
);

/*VERIFY DATE STRING WAS PARSED*/
//check to make sure a DateTime object was returned
//to verify that the date string was of the correct
//format and was thus parsed
if ( !($server_date_time instanceof DateTime) ) {
$error_array = DateTime::getLastErrors();
throw new Exception( implode(" - ",$error_array['errors']) );
}

//convert DateTime object to Unix time stamp
$server_time = strtotime($server_date_time->format('d-m-Y H:i:s'));
echo "Unix time stamp : $server_time\n";
} catch (Exception $e){
echo $e->getMessage().' at line '.$e->getLine().' in file '.$e->getFile();
}



comments powered by Disqus