PHP

PHP Date Format Example

In this example, we shall show how to deal with dates in PHP. As dates can be represented in many different ways. It is important to find a way that helps to avoid possible unexpected errors that may arise.

For this example, we will use:

  • Ubuntu (14.04) as Operating System.
  • Apache HTTP server (2.4.7).
  • PHP (5.5.9).

 
 

Tip
You may skip environment preparation creation and jump directly to the beginning of the example below.

1. Preparing the environment

1.1. Installation

Below, commands to install Apache and PHP are shown:

sudo apt-get update
sudo apt-get install apache2 php5 libapache2-mod-php5
sudo service apache2 restart

Note: if you want to use Windows, installing XAMPP is the fastest and easiest way to install a complete web server that meets the prerequisites.

2. How should dates be stored?

As you will probably know, the date representation varies from region to region. For example, in UK, we would say that today is 13/05/2016; whereas in US, we would represent it as 05/13/2016.

This can lead to a problem. If we have a system that needs to do some calculations basing on the date, if a date is in an unexpected format, we would have nonsense results.

To solve this, a system known as Unix time, also known as Epoch time was proposed. What this system does, is describe time instants: it’s defined as the number of seconds passed from 01/01/1970 at 00:00:00 (UTC). So, the date we mentioned above, in Unix time, would be 1463097600 (truncated to the day start, at 00:00:00).

We could define it as a “cross-region/language time representation”.

The Unix time is universally used not only in Unix-like systems, but also in many other computational systems. So, with Unix time, we have widely used standard that does not depend on any region or system configuration. In the case a user has to deal with this data, the only thing we would have to do is to transform it to a human-readable format.

Note: Unix time is not a real representation of UTC, as it does not represent leap seconds that UTC does.

3. PHP examples

3.1. From time stamp to human-readable

Below, we are seeing how to get the current time stamp, and to get a formatted date:

timestamp_to_human.php

<?php

$timestamp = time();
$date = date('d-m-Y', $timestamp);
$datetime = date('d-m-Y h:i:s', $timestamp);

echo "Unix timestamp: $timestamp <br>";
echo "Human-readable date: $date <br>";
echo "Human-readable datetime: $datetime";

The date() function supports a wide list of formats, some of them are:

  • l for day name.
  • N for day number of the week, being Monday the first.
  • z for day number of year.
  • W for month number of year.

Updating the script to use them:

timestamp_to_human.php

echo 'Day name: ' . date('l', $timestamp) . '<br>';
echo 'Day number of week: ' . date('N', $timestamp) . '<br>';
echo 'Day number of year: ' . date('z', $timestamp) . '<br>';
echo 'Month number of year: ' . date('W', $timestamp) . '<br>';

Note: the second parameter, were we have specified the time stamp, is optional. If we don’t specify any time stamp, current will be used.

3.2. From human-readable to time stamp

Now, the reverse process: from human-readable format, to Unix time stamp:

human_to_timestamp.php

<?php

$ukDate = '13-05-2016'; // For UK format, '-' must be the separator.
$usDate = '05/13/2016'; // For US format, '/' must be the separator.

$ukTimestamp = strtotime($ukDate);
$usTimestamp = strtotime($usDate);

echo "Timestamp created from UK date format: $ukTimestamp <br>";
echo "Timestamp created from US date format: $usTimestamp";

strtotime() function does the job. Additionally, the function supports expressions like:

  • Adverbs, like now, tomorrow; and next Friday, last Saturday, etc.
  • Mathematical expressions, e.g., +2 weeks 5 days 12 hours.

Let’s see it:

human_to_timestamp.php

echo "Tomorrow's time stamp is: " . strtotime('tomorrow') . '<br>';
echo 'And in 2 weeks, 5 days and 12 hours time: ' . strtotime('+2 weeks 5 days 12 hours') . '<br>';

3.3. DateTime class

Apart from those functions, it is also available a class named DateTime, with some useful methods.

We can, for example, calculate the difference between two dates:

difference_with_datetime.php

<?php

$currentDate = new DateTime();
$targetDate = new DateTime('19-01-2038'); // Date when Unix timestamp will overflow in 32 bits systems!

$timeLeft = $currentDate->diff($targetDate);

$yearsLeft = $timeLeft->y;
$monthsLeft = $timeLeft->m;
$daysLeft = $timeLeft->d;
$hoursLeft = $timeLeft->h;
$minutesLeft = $timeLeft->i;
$secondsLeft = $timeLeft->s;

echo "Time left to Unix timestamp overflow in 32 bits systems:
";
echo "| $yearsLeft years | $monthsLeft months | $daysLeft days | $hoursLeft hours | $minutesLeft minutes | $secondsLeft seconds |";

As we can see, we can specify a date when instantiating DateTime class, or we cannot specify it in order to use the current datetime.

3.4. Increasing precision

In some scenarios, it could occur that the time stamp precision is not enough. For these occasions, we have available the microtime() function, which gets the current Unix time, with microseconds. Let’s see an example with this:

datetime_with_microseconds.php

<?php

$microtime = microtime();

list($microseconds, $seconds) = explode(' ', $microtime);

$microseconds = str_replace('0.', '', $microseconds);

$datetime = date('d-m-Y h:i:s');
$datetime .= ':' . $microseconds;

echo "Current datetime with microseconds: $datetime";

For some reason, microtime() function returns a string with the following format: <microseconds> <seconds>, separated by a blank space. So, we have to split it.

The microseconds are expressed as real number, so, we should remove the leading zero integer part. Then, we can manually add to the formatted datetime the microseconds part.

The funny fact is that, actually, the date() function does support the microseconds formatter, ‘u’. But it’s not able to generate the microseconds. If you try to get a date using date('d-m-Y h:i:s:u');it will generate only zeros in the microseconds part. What were PHP developers thinking in?

3.5. Validating user introduced date

If we are having a web page where the user has to introduce same date, probably, we will use a JQuery plugin to allow the user select the date graphically. In any case, after performing any operations, we should ensure that the date is correct.

If you try to calculate the time stamp of a nonsense date, for example, 40/15/2016, you will receive the following time stamp: 1555279200, with no error. And, if you try to calculate the date of that time stamp, you will receive a correct date, 14/04/2019.

Depending on the scenario, this can be something to check, or not. If you are expecting a date introduced by an user, normally, we want to ensure that it is actually a valid date expressed in human-readable format. Let’s see how we would validate it in the following example:

validate_date.php

<?php

define('DEFAULT_DATE_SEPARATOR', '-');
define('DEFAULT_DATE_FORMAT', 'd' . DEFAULT_DATE_SEPARATOR . 'm' . DEFAULT_DATE_SEPARATOR . 'Y'); // 'd-m-Y'.

/**
 * Checks the validity of the date, using "checkdate()" function. Leap years are also taken into consideration.
 *
 * @param $date The input date.
 * @return True if the date is valid, false if it is not.
 */
function validateDate($date) {
    list($day, $month, $year) = explode(DEFAULT_DATE_SEPARATOR, $date);

    $validDate = checkdate($month, $day, $year); // Not a typo; the month is the first parameter, and the day the second.

    return $validDate;
}

// Flow starts here.

$inputDate = $_GET['input-date'];
$validDate = validateDate($inputDate);

if ($validDate) {
    $response = "The date $inputDate is valid.";
} else {
    $response = "Error: the date $inputDate is not correct.";
}

echo $response;

Fortunately, PHP has a built-in function for this cases, named checkdate(), that checks the validity of a Gregorian date, considering also leap years. So, 29-02-2016 would be considered valid, while 29-02-2015 wouldn’t.

The problem here is that we have to parse manually the date, to extract the day, month and year, and also to the specified format. If we use any other function to change the format, or to retrieve the date numbers, it would automatically fix the date, doing the same as we saw before the example, so we could not validate the date.

4. Summary

We have seen that saving dates in any human-readable format is not a good idea, because the same date can have many different representations, which will depend on the region. We have seen that Unix time format solves this, using a portable format, that does not rely on region or languages, and how to deal with this format in PHP.

5. Download the source code

This was an example of date formatting with PHP.

Download
You can download the full source code of this example here: PHPDateFormatExample
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button