In PHP there is an easy way to convert a string to date format. And it will work in all situation flawlessly.

Problem

Let’s say that we have this date in string format that we want to change to date format in PHP:

$olddate = '2008-07-01T22:35:17.02';

Basic and the old way.

The easist way is to use combination between strtotime() and date(). Basically, strtotime() function will Parse about any English textual datetime date into a Unix Timestamp. With this a Unix TImestamp, we can pass it  to date() function to change it to another format.

$timestamp = strtotime($olddate);
$new_date_format = date('Y-m-d H:i:s', $timestamp);

What is The Unix timestamp

The Unix timestamp is a measurement to track time as a running total of seconds and starts at the Unix Epoch on January January 1 1970 00:00:00 GMT.

DateTime class ( PHP 5.3 and above)

As of PHP 5.2, PHP has introduced a new feature called the DateTime() class which allow us to rewrite the above code as follows:

$date = new DateTime($olddate );
$new_date_format = $date->format('Y-m-d H:i:s');

Use DateTime class offers us more powerful tools when we are working with dates.

Working with non-standard and ambiguous date formats

Another reason to use this class is when we as developer sometimes get nonstandard format.  Fortunately, PHP 5.3 has offered us an excellent tool to solve this problem.

DateTime::createFromFormat() allows us to  parses a time string according to a specified format so it can be successfully change into Datetime object for further manipulation.


$date = DateTime::createFromFormat('F-d-Y h:i A', 'April-18-1973 9:48 AM');
$new_$newformat = $date->format('Y-m-d H:i:s');

If you have already moved to this version of PHP, I recommend you to use this class. It will give you more freedom what you can do with the date in PHP.