string date ( string $format [, int $timestamp = time() ] )
int strtotime ( string $time [, int $now ] )
Convert a date into another format
The simplist way to convert one date format into another is to use strtotime() with date(). strtotime() will convert the date into a Unix Timestamp. That Unix Timestamp can then be passed to date() to convert it to the new format.
Or as a one-liner:
Keep in mind that strtotime() requires the date to be in a valid format. Failure to provide a valid format will result in strtotime() returning false which will cause your date to be 1969-12-31.
As of PHP 5.2, PHP offered the DateTime() class which offers us more powerful tools for working with dates (and time). We can rewrite the above code using DateTime() as so:
Working with Unix timestamps
date() takes a Unix timestamp as its second parameter and returns a formatted date for you:
DateTime() works with Unix timestamps by adding an @ before the timestamp:
If the timestamp you have is in milliseconds (it may end in 000 and/or the timestamp is thirteen characters long) you will need to convert it to seconds before you can can convert it to another format. There's two ways to do this:
Trimming the last three digits can be acheived several ways, but using substr() is the easiest:
Divide the substr by 1000
You can also convert the timestamp into seconds by dividing by 1000. Because the timestamp is too large for 32 bit systems to do math on you will need to use the BCMath library to do the math as strings:
To get a Unix Timestamp you can use strtotime() which returns a Unix Timestamp:
If you're running PHP 5.2 you can use the U formatting option instead:
Working with non-standard and ambiguous date formats
Unfortunately not all dates that a developer has to work with are in a standard format. Fortunately PHP 5.3 provided us with a solution for that. DateTime::createFromFormat() allows us to tell PHP what format a date string is in so it can be successfully parsed into a DateTime object for further manipulation.
In PHP 5.4 we gained the ability to do class member access on instantiation has been added which allows us to turn our DateTime() code into a one-liner:
Unfortunately this does not work with DateTime::createFromFormat() yet.
Getting the difference between two dates / times
The most feasible way is to use, the DateTime class.