Converting between dates and timestamps in PHP

September 23, 2015, 10:05 pm
Author: James Griffiths

There may be occasion, when working in PHP, that you need to convert date related values between date type formats and timestamps.

PHP makes that incredibly easy to accomplish.

Using the date object we can construct a specific date and display it as easily as this:

$date = date('2015-09-21 09:00:00');
echo $date;

// Outputs: 2015-09-21 09:00:00

Now if we want to convert the above date to a timestamp we can simply use the strtotime method:

$timestamp = strtotime($date);
echo $timestamp;

// Outputs: 1442822400

Great!

Now what if we find ourselves needing to convert that timestamp back to a date?

We might, as an example, have 2 different database systems where data is written into - one accepting timestamps for the date related field while the other accepts only a year-month-day hour:minute:second formatted date instead - how do we convert the data between the 2 different field types?

Simple. Taking the above timestamp object we can do this:

$newDate = date('Y-m-d H:i:s', $timestamp);
echo $newDate;

// Outputs: 2015-09-21 09:00:00

By specifying the particular date format we can convert the timestamp into whatever date we desire.

We could, for example, do the following:

$shortDate = date('Y-m-d', $timestamp);
echo $shortDate;

// Outputs: 2015-09-21

Or output a date in this format instead:

$differentDate = date('j F y', $timestamp);
echo $differentDate;

// Outputs: 21 September 15

Thanks to PHP's built in support for date handling switching between generating timestamps and dates is quick and easy to accomplish.

Categories

« Return to Posts

Post a comment

All comments are welcome and the rules are simple - be nice and do NOT engage in trolling, spamming, abusiveness or illegal behaviour. If you fail to observe these rules you will be permanently banned from being able to comment.