Convert a string to a date in PHP

The following code converts a string to a date (DateTime) object in PHP.  The DateTime object provides a consistent method for handling dates in your PHP code.

<?php

// Create a format string based on the formats listed
// here: http://www.php.net/manual/en/datetime.formats.date.php
$date_format = "!m/d/Y";

// The date string we want to convert
$date_string = "12/11/2013";

// Now convert the string to a DateTime object using the format specified
$date_obj = DateTime::createFromFormat($date_format,$date_string);

// Get the unix timestamp value
$date_timestamp = $date_obj->getTimestamp();

// Output the result
print $date_string . " has a unix timestamp of " . $date_timestamp;

?>

You can see that the code we are using to accomplish this is primarily using the createFromFormat factory method of the DateTime object.   It simply takes the date format as a string and the string that you are looking to parse.  There are other functions like date_parse that can be used to parse a date string in PHP, however this does not use a fixed format and therefore can result in an unexpected result when parsing a date.

The third parameter of the createFromFormat method is a timezone and should be used if your application is accepting dates/times from people in multiple timezones.

Happy coding!

Leave a Comment