Skip to main content

Convert a date using php

Updated by Tim Rabbetts on
coding, programming, css

The easiest way to convert a date in php I find is to use the php date and strtotime function.

The strtotime function will parse about any English textual datetime description into a Unix timestamp.  Here are some examples of what can be parsed into a unix timestamp.

Once you have the timestamp, you can pass it to the date function which will allow you to format the unix timestamp into a multitude of different formats.

Now the about code will only take the exact time the script ran and out put that in the given format.  If you want a specific date you need to do the following.

The result of the print command would be “Monday 1st of August”.

echo strtotime("now"), "\n";
echo strtotime("10 September 2000"), "\n";
echo strtotime("+1 day"), "\n";
echo strtotime("+1 week"), "\n";
echo strtotime("+1 week 2 days 4 hours 2 seconds"), "\n";
echo strtotime("next Thursday"), "\n";
echo strtotime("last Monday"), "\n";

// set the default timezone to use. Available since PHP 5.1
date_default_timezone_set('UTC');

// Prints something like: Monday
echo date("l");

// Prints something like: Monday 8th of August 2005 03:12:46 PM
echo date('l jS \of F Y h:i:s A');

// Prints: July 1, 2000 is on a Saturday
echo "July 1, 2000 is on a " . date("l", mktime(0, 0, 0, 7, 1, 2000));

/* use the constants in the format parameter */
// prints something like: Mon, 15 Aug 2005 15:12:46 UTC
echo date(DATE_RFC822);

// prints something like: 2000-07-01T00:00:00+00:00
echo date(DATE_ATOM, mktime(0, 0, 0, 7, 1, 2000));

$my_old_date = '18-08-2010';

$my_new_date = date('l jS \of F Y',strtotime($my_old_date));

print $my_new_date;

 

Add new comment