Random thoughts & observations

From the mundane to the profound and everything in between here’s what’s rocking our world

Converting between dates and timestamps in PHP

Posted: September 23, 2015
Written by: Saints At Play
Category: Server

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


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.

« Return to Posts


There are no comments

Posting comments after three months has been disabled.