The complete guide on working with dates and time in PHP
  John Mwaniki /   27 Aug 2021

The complete guide on working with dates and time in PHP

As a developer, nearly every application you will work on requires the use of time in some way. You will need to keep a record of the time in which various activities occur, such as the time in which a record is created, updated, deleted, when a user logs in, etc.

At some point, you’re going to have to collect, store, retrieve and display dates and times in different formats. You are also likely to do calculations involving time such as adding days to a day, subtracting a number of days from a date, comparing two days, etc.

In this article, we will cover in detail working with dates and times in PHP.

How computers count time

Computers count time from an instant called Unix epoch, which occurred on January 1, 1970, at 00:00:00 UTC(Coordinated Universal Time). UTC is also known as GMT(Greenwich Meridian Time), which is the time at a longitude of 0°.

Unix time elapses at the same rate as UTC. You can calculate the UTC date and time of any given instant since January 1, 1970, by counting the number of seconds since the Unix epoch, with the exception of leap seconds. Leap seconds are occasionally added to UTC to account for the slowing of the Earth’s rotation but are not added to Unix time.

Unix Timestamp

Unix timestamp is the number of seconds that have elapsed since January 1, 1970, at 00:00:00 UTC.

Standard Dates Reporting

Computers count time using Unix timestamp, calculating the number of seconds that have passed since Jan 1, 1970. However, this would be difficult and incredibly inefficient for humans. Thus, we work in terms of years, months, days, hours, minutes, and seconds.

But this also comes with complexities because different regions and cultures have different ways of writing the date. For instance, dates in the United States are written starting with the month, then day, then the year. December 31, 2021, will be written as 12-31-2021. On the other hand, the same date will be written as 31-12-2021 in Europe and other regions.

To standardize the date and help fix the communication mistakes, the International Organization for Standardization (ISO) introduced ISO8601. This standard specifies that all dates should be written in order of most-to-least-significant data. This means the format is the year, month, day, hour, minute, and second:


YYYY-MM-DD HH:MM:SS

In the example above, YYYY represents a four-digit year, and MM and DD are the two-digit month and day, starting with a zero if less than 10. After that, HH, MM, and SS represent the two-digit hours, minutes, and seconds, starting with a zero if less than 10.

The above format eliminates the ambiguity in dates representation, where dates written as DD-MM-YYYY or MM-DD-YYYY can be misinterpreted if the day is a valid month number.

Most databases use YYYY-MM-DD HH:MM:SS format to store date and time and YYYY-MM-DD to store date.

Setting and getting timezone on your server

Different regions of the world have different timezones. You can know which timezone your web server is set to with the following PHP function.

<?php
$timezone = date_default_timezone_get();
echo "The server is set to: ".$timezone;

To change to the timezone that will be used in your date and time functions in PHP, you do it with the function date_default_timezone_set($timezoneId), where $timezoneId is a string value.

Example:

<?php
date_default_timezone_set("Africa/Nairobi");

The above code sets the timezone to that of Nairobi, Kenya. You can get a list of all timezones on this link

Unless all your website/app users are from the same region, it is always advisable to set your server time zone to UTC.

Below is how you set timezone to UTC in PHP:

<?php
date_default_timezone_set("UTC");

For the date and time functions to pick and reflect the timezone specific time, you should always the function for setting the timezone at the top.

Timestamp function: time()

The function returns the current unix timestamp, ie. total number of seconds that have passed since January 1, 1970 at 00:00:00 UTC.

<?php
$timestamp = time();
echo $timestamp;

 

PHP date() function

The function returns a string formatted according to the given format string using the given integer timestamp.

It takes the format below:


date($format, $timestamp)

Where $format is a string value and $timestamp an optional integer unix timestamp value.If $timestamp is not given, the function defaults to the value of time()


date($format)

 

Date function formatting options

String Value Description
Y 4-digit year eg. 2021
y 2-digit year eg. 21
F Name of the Month eg. August
M Short-form name of the month eg. Aug
m The number of the month eg. 01 for January
n A numeric representation of a month, without leading zeros (1 to 12)
t The number of days in the given month
l (Lower case L) Long-form day of the week eg. Monday
W ISO-8601 Week number of the year (Weeks starting on Monday)
N ISO-8601 numeric number of the day of the week (1 for Mon, 7 for Sun)
w Numeric representation for a day of the week (0 for Mon, 6 for Sat)
D Short-form(3-letter) day of the week eg. Mon
d Day of the month (01 - 31)
j Day of the month without leading zeros (1 - 31)
z The day of the year (from 0 through 365)
S The English ordinal suffix for the day of the month eg. st, nd, rd, th. Works best when used in combination with j.
H The hour in 24hr system (00 - 23)
h The hour in 12hr system (01 - 12)
G 24-hour format of an hour without leading zeros (0 to 23)
g 12-hour format of an hour without leading zeros (1 to 12)
i Minutes with leading zeros (00 to 59)
s Seconds with leading zeros (00 to 59)
A Sets uppercase AM or PM
a Sets lowercase am or pm
L Returns whether it's a leap year (1 if it is a leap year, 0 otherwise)

To convert/format a date in different formats using the date() function, you need to first convert that date into a Unix timestamp using the strtotime() function.

Conversion of date/time to Unix timestamp

The strtotime() function parses an English textual datetime into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 GMT).

Syntax:


strtotime(time, now);
Parameter Description
time Required. Specifies a date/time string
now Optional. Specifies the timestamp used as a base for the calculation of relative dates

Example

<?php
$date = "2021-08-27 13:19:00";
$timestamp = strtotime($date);
echo $timestamp;

Example 2: Displaying current time in DateTime format

<?php
//Displays current date and time as YYYY-MM-DD HH:MM:SS
echo date("Y-m-d H:i:s");

 

Converting a date into different formats

<?php
$date = "2021-08-27 13:19:00";

//Displaying the date as 27th August, 2021
echo date("jS F, Y", strtotime($date));

//Displaying the date as Friday 27th Aug, 2021
echo date("l jS M, Y", strtotime($date));

//Displaying the date as 27-08-2021
echo date("d-m-Y", strtotime($date));

//Displaying the date as 27/08/2021
echo date("d/m/Y", strtotime($date));

//Displaying the date as Friday 27th Aug, 2021 at 1:19pm
echo date("l jS M, Y \\a\\t g:i a", strtotime($date));

You can convert the date into as many formats as possible by just manipulating various letters in the table above to form within the date() function, enclosed in single or double-quotes.

 

Adding and subtracting days or time to a DateTime

The easiest way to add or subtract time to/from date in PHP is by concatenating a string specifying the duration of time you want to add or subtract, to date, inside the strtotime() function, preceded with the plus (+) or minus (-) symbol.

Example 1

Adding time to the current time

<?php
//Adding 5hrs to the current time
$latertime =  date("Y-m-d H:i:s", strtotime(" + 5 hours"));
echo "5 hours from now, the time will be ".$latertime;

Example 2

Adding time to a DateTime

<?php
$date = "2021-08-27 13:19:00";

//Adding 3hrs to the date and time above
echo date("Y-m-d H:i:s", strtotime($date." + 3 hours"));

//Subtracting 5hrs from the date and time above
echo date("Y-m-d H:i:s", strtotime($date." - 5 hours"));

Example 3

Adding days, weeks, months and years to a date

<?php
$date = "2021-08-27";

//Adding 2 days to a date
echo date("Y-m-d", strtotime($date." +2 days"));

//Adding 3 weeks to a date
echo date("Y-m-d", strtotime($date." +3 weeks"));

//Subtracting 4 months from a date
echo date("Y-m-d", strtotime($date." -4 months"));

//Adding 1 year to a date
echo date("Y-m-d", strtotime($date." +1 year"));

 

How to subtract 2 dates in PHP

When you have two dates that you want to find their difference, PHP can help you find it.

You just convert the two dates to unix timestamps, subtract the two timestamps and find the difference between the two dates in seconds.

You then convert the time in seconds to the duration in which you want to measure the time in eg. hours, days, years, etc.

Example

<?php
$date1 = "2021-01-27";
$date2 = "2021-08-27";

//Display the difference between the two dates in seconds
echo strtotime($date2)-strtotime($date1);

//Displaying time difference in hours
// 1hr = 3600secs
$difference = strtotime($date2)-strtotime($date1);
echo "Difference is: ".$difference/3600." hours";


//Displaying time difference in days
// 1day = 86400secs
$difference = strtotime($date2)-strtotime($date1);
echo "Difference is: ".$difference/86400." days";

If you use DateTime format(date and time in the date), use the floor() function to round down and avoid decimals in time difference like below.

<?php
$date1 = "2021-01-27 10:15:23";
$date2 = "2021-08-27 13:19:00";
$difference = strtotime($date2)-strtotime($date1);
echo "Difference is: ".floor($difference/86400)." days";

 

Comparison between 2 dates

It is quite easy to compare two dates and know which is older than the other.

If the two dates are exactly in the same format, you just compare them directly as below:

<?php
$date1 = "2021-01-27";
$date2 = "2021-08-27";

if($date1 > $date2){
  echo $date1. " is greater than ".$date2;
}
else{
  echo $date2. " is greater than ".$date1;
}

If the two dates have different formats, you will first need to convert the two to the Unix timestamp, then compare them as below.

<?php
$date1 = "2021-01-27";
$date2 = "Friday 27 Aug, 2021";

//Conversion to Unix timestamp
$timestamp1 = strtotime($date1);
$timestamp2 = strtotime($date2);

if($timestamp1 > $timestamp2){
   echo $date1. " is greater than ".$date2;
}
else{
   echo $date2. " is greater than ".$date1;
}

 

Conclusion

Nearly in all applications, you will ever work on as a developer, in whatever language you decide to use, you will have to work with dates and time in one way or another.

In this article, we have covered working with dates in PHP.  We have covered how computers count time, what Unix timestamp is, how to collect the current time, working with timezones, converting dates and time into multiple different formats, adding or subtracting time to or from a date, and dates comparison among other things.