Format date time

Hey guys,
Have you tried to format something like this —> Fri, 07 Oct 2011 23:28:23
THEN TURN INTO THIS -------> 2011-10-07 23:28:23?

Thanks for the help guys…

First of all, you’ll want to use the following string to format your final date:


$dateFormat = 'Y-m-d H:i:s';

You could just pass that to the date function (“date($dateFormat)”), but that would just format the current date/time. To format an arbitrary date, you also have to pass it a Unix timestamp, like so:


$final = date($dateFormat, $unix);

And you can get a Unix timestamp from a well-formatted string with the strtotime function:


$starting = 'Fri, 07 Oct 2011 23:28:23';
$unix = strtotime($starting);

So when it’s all said and done, your code would look something like this:


$starting = 'Fri, 07 Oct 2011 23:28:23';
$unix = strtotime($starting);
$dateFormat = 'Y-m-d H:i:s';
$final = date($dateFormat, $unix); // should return '2011-10-07 23:28:23'

$old= "Fri, 07 Oct 2011 23:28:23";
$tgt = "2011-10-07 23:28:23";

$new = date('Y-m-d H:i:s',strtotime($old));
if( $new === $tgt ) echo 'Bingo!';

If $old is coming from a dubious source also look at [fphp]checkdate[/fphp].

All the date format options are listed in the manual [fphp]date[/fphp].

If you’re lucky enough to be allowed to use PHP 5.3 (and you should be, since the PHP Group no longer support 5.2), then you can easily take your input date and format it exactly how you like.


$subject   = "Fri, 07 Oct 2011 23:28:23";
$datetime  = DateTime::createFromFormat("D, d M Y H:i:s", $subject);
$formatted = $datetime->format("Y-m-d H:i:s");

The above is the preferred option when you know the format of the date string coming in. If you’re not using PHP 5.3, or the input date string varies in format, then new DateTime(…) or strtotime(…) can be used so long as it consists of supported date/time formats.

More info:

Hi guys
Thanks for the interesting replies, hmmmm… It says on my xampp panel the php is 5.3.* how come Salathe’s code didn’t work.
I just followed the code and he give an error Fatal error: Call to a member function format() on a non-object

Thanks CUPS it worked, Thanks also sdleihssirhc for the reply.

This is SOLVED!