From accurately tracking the opening and closing of financial markets to preserving the history of posts and research papers by properly saving the times they were created, edited, and deleted, software engineers must understand how to handle dates and times in their applications.

The concept of dates and times is especially important in programming. All programming languages enable developers to manage dates and times in their applications. In this article, you will learn everything you need to know about PHP dates and times and how to use them effectively in your applications.

Prerequisites

To follow along with this tutorial, you will need to understand the basics of PHP. Knowledge of variables, functions, objects, and classes will also be helpful.

However, concepts covered in the article will be explained before they are used.

Important: There is a timing flaw in the original date and time functions when used on Windows and specific Unix installations. These functions cannot effectively process dates before December 13, 1901, or after January 19, 2038. This limitation arises from the utilization of a 32-bit signed integer for date and time management. To ensure greater accuracy, it is advised to employ the DateTime class family.

Working with dates in PHP

PHP provides a DateTime class with a rich set of methods for manipulating them. In this section, I will explore these methods and what they enable you to do in your applications.

Parsing dates in PHP

Parsing is the process of converting a string value into a date object. For example, if you get a user's date of birth from a form on your application, you need to convert the string into a date object that you can use for further processing in your code.

Here's an example:

$birthday = '2002-09-12';
$date = DateTime::createFromFormat('Y-m-d', $birthday);

echo "Your birthday is on " . $date->format('l, F jS, Y') . "<br> <br>";

The code above defines a birthday variable, representing the value of a birthday field in a form. It uses createFromFormat to format it in the year-month-day format using the designated letters. Finally, it prints out a message that looks like the following to the user:

Your birthday is on Sunday, September 3rd, 2002

Understanding format characters

In PHP, you can use various predefined date formats by using format characters with the DateTime class. Here are some commonly used predefined date formats:

  1. Y - Year with four digits (e.g., "2023").
  2. y - Year with two digits (e.g., "23").
  3. F - Full month name (e.g., "September").
  4. M - Abbreviated month name (e.g., "Sep").
  5. m - Month as a zero-padded number (e.g., "09").
  6. n - Month as a number without leading zeros (e.g., "9").
  7. d - Day of the month as a zero-padded number (e.g., "08").
  8. j - Day of the month as a number without leading zeros (e.g., "8").
  9. D - Abbreviated day of the week (e.g., "Mon").
  10. l - Full day of the week (e.g., "Monday").
  11. N - ISO-8601 numeric representation of the day of the week (1 for Monday, 7 for Sunday).
  12. w - Numeric representation of the day of the week (0 for Sunday, 6 for Saturday).
  13. W - ISO-8601 week number of the year (e.g., "37").
  14. z - Day of the year (0 through 365).
  15. G - Hour in 24-hour format without leading zeros (e.g., "9" or "23").
  16. H - Hour in 24-hour format with leading zeros (e.g., "09" or "23").
  17. i - Minutes with leading zeros (e.g., "05").
  18. s - Seconds with leading zeros (e.g., "07").
  19. a - Lowercase AM or PM (e.g., "am" or "pm").
  20. A - Uppercase AM or PM (e.g., "AM" or "PM").
  21. U - Unix timestamp (seconds since the Unix epoch).
  22. S - Adds "nd", "rd", "th", etc. at the end of numeric dates
  23. r - "-" If the difference is negative; empty if the difference is positive.
  24. R - "–" If the difference is negative; "+" if the difference is positive.

As shown in the previous code block, these format characters can be combined to create custom date formats according to your specific needs.

Parsing relative dates

PHP enables you to easily parse relative dates, such as tomorrow, next week, the following Monday, etc. using the strtotime function or format method. Here are some examples:

$tommorow = 'tomorrow';
$date = new DateTime($tommorow);
echo "Tommorow's date is: " .  $date->format('Y-m-d, l') . "<br>";

$nextWeek = strtotime('next week');
echo "Exactly a week from now is: " .  date('Y-m-d, l', $nextWeek) . "<br>";

$nextMonth = strtotime('next month');
echo "Next month is: " .  date('F Y', $nextMonth). "<br>"; 

$next2Month = strtotime('next 2 months');
echo "Any unsupported string will return: " . date('F Y', $next2Month). "<br>"; 

$secondMondayOfNextMonth = strtotime('second monday of next month');
echo "Second Monday of next month is: " .  date('l Y-m-d', $secondMondayOfNextMonth). "<br>";

$lastDayNextMonth = strtotime('last day of next month');
echo "Last day of next month is: " .  date('l Y-m-d', $lastDayNextMonth). "<br>";

$twoWeeksAgo = strtotime('2 weeks ago');
echo "Exactly 2 weeks from now is: " .  date('l Y-m-d', $twoWeeksAgo). "<br>"; 

$nextMonday = strtotime('next monday');
echo "Next Monday's date is: " .  date('l Y-m-d', $nextMonday). "<br>";

$nextFriday = strtotime('next friday');
echo "Next Friday's date is: " .  date('l Y-m-d', $nextFriday). "<br>";

$twoDaysFromNow = strtotime('2 days');
echo "Exactly 2 days from now is " .  date('l Y-m-d H:i:s', $twoDaysFromNow). "<br>";

The code above defines supported strings as variables with the strtotime function, which converts them into date objects. The code above should return a result similar to the following depending on when you run the code:

Tomorrows date is: 2023-09-13, Wednesday
Exactly a week from now is: 2023-09-18, Monday
Next month is: October 2023
Any unsupported string will return: January 1970
Second Monday of next month is: Monday 2023-10-09
Last day of next month is: Tuesday 2023-10-31
Exactly 2 weeks from now is: Tuesday 2023-08-29
Next Monday's date is: Monday 2023-09-18
Next Friday's date is: Friday 2023-09-15
Exactly 2 days from now is Thursday 2023-09-14 15:46:59

Note: Any unsupported string will return a default date of January 1970 00:00:00, depending on how you format the result.

Formatting dates

Formatting dates converts date objects into readable strings that users can understand. Here's an example:

$currentDateTime = new DateTime();
echo $currentDateTime->format('Y-m-d H:i:s');

The code above defines a $currentDate variable that creates a new date object with the current date and returns the date object in a readable format using some formatting characters covered in the previous section.

Formatting timestamps

Converting timestamps to readable strings is straightforward in PHP thanks to the format method. Here’s an example:

$timestamp = 1694531229;
$date = new DateTime('@' . $timestamp);
echo $date->format('Y-m-d H:i:s');

The code above defines a $timestamp variable and converts it into a readable format that looks like the following using the format method:

2023-09-12 15:07:09

Note: You need to prefix the timestamp with the @ symbol to successfully convert the timestamp. Alternatively, you can also store the timestamp variable as a string: @1694531229; thus, you can omit the @ symbol in the format method.

Manipulating dates

Manipulating dates is the process of computing dates as needed in your application. Examples of these include adding and subtracting dates. Let's learn how to do this in the following sections.

Adding to dates in PHP

PHP provides an add function and a DateInterval class that you can use to add to dates. Here's an example:

$date = new DateTime('2023-09-12');
$date->add(new DateInterval('P5D'));
echo $date->format('Y-m-d');

The code above defines a string date variable, uses the add function to add five days, and then prints the new date. The code above should return the following:

2023-09-17

Let's see how to add weeks, months, and years to dates in another example:

$twoWeeks = new DateTime('2023-09-12');
$twoWeeks->add(new DateInterval('P2W')); 
echo "Given date plus two weeks = " . $twoWeeks->format('l, Y-m-d'); 

$threeMonths = new DateTime('2023-09-12');
$threeMonths->add(new DateInterval('P3M'));
echo "<br> Given date plus 3 months = " . $threeMonths->format('l, Y-m-d');

$fourYear = new DateTime('2023-09-12');
$fourYear->add(new DateInterval('P4Y'));
echo "<br> Given date plus 4 years = " . $fourYear->format('l, Y-m-d');

The code above will return the following result:

Given date plus 2 weeks = Tuesday, 2023-09-26
Given date plus 3 months = Tuesday, 2023-12-12
Given date plus 4 years = Sunday, 2027-09-12

PHP provides a modify function that allows you to achieve the same result:

$twoWeeks = new DateTime('2023-09-12');
$twoWeeks->modify('+2 weeks'); 
echo "Given date plus two weeks = " . $twoWeeks->format('l, Y-m-d'); 

$threeMonths = new DateTime('2023-09-12');
$threeMonths->modify('+3 months');
echo "<br> Given date plus 3 months = " . $threeMonths->format('l, Y-m-d');

$fourYear = new DateTime('2023-09-12');
$fourYear->modify('+4 years');
echo "<br> Given date plus 4 years = " . $fourYear->format('l, Y-m-d');

The code above will return the same result as the previous code block.

Subtracting from dates in PHP

Subtracting dates is the same process as adding dates but with a sub function instead of the add function. Here's an example:

$oneDay = new DateTime('2023-09-12');
$oneDay->sub(new DateInterval('P1D')); 
echo "Given date minus one day = " . $oneDay->format('l, Y-m-d'); 

$twoWeeks = new DateTime('2023-09-12');
$twoWeeks->sub(new DateInterval('P2W')); 
echo "<br> Given date minus 2 weeks = " . $twoWeeks->format('l, Y-m-d'); 

$threeMonths = new DateTime('2023-09-12');
$threeMonths->sub(new DateInterval('P3M'));
echo "<br> Given date minus 3 months = " . $threeMonths->format('l, Y-m-d');

$fourYear = new DateTime('2023-09-12');
$fourYear->sub(new DateInterval('P4Y'));
echo "<br> Given date minus 4 years = " . $fourYear->format('l, Y-m-d');

The code above subtracts days, weeks, months, and years from the given dates and returns the following result:

Given date minus 1 day = Monday, 2023-09-11
Given date minus 2 weeks = Tuesday, 2023-08-29
Given date minus 3 months = Monday, 2023-06-12
Given date minus 4 years = Thursday, 2019-09-12

You can achieve the same result with the modify function:

$oneDay = new DateTime('2023-09-12');
$oneDay->modify('-1 day'); 
echo "Given date minus one day = " . $oneDay->format('l, Y-m-d'); 

$twoWeeks = new DateTime('2023-09-12');
$twoWeeks->modify('-2 weeks'); 
echo "<br> Given date minus 2 weeks = " . $twoWeeks->format('l, Y-m-d'); 

$threeMonths = new DateTime('2023-09-12');
$threeMonths->modify('-3 months');
echo "<br> Given date minus 3 months = " . $threeMonths->format('l, Y-m-d');

$fourYear = new DateTime('2023-09-12');
$fourYear->modify('-4 years');
echo "<br> Given date minus 4 years = " . $fourYear->format('l, Y-m-d');

The code above will return the same result as the previous one.

Now that you understand how to parse, format, and manipulate dates, let's explore how to handle times in the next section.

Working with times in PHP

Working with times in PHP is also relatively easy thanks to the DateTime class and its functions.

Arithmetic operations on times in PHP

Performing an arithmetic operation on times is a common use case in PHP. Here's how to add seconds, minutes, and hours to times in PHP:

$addSeconds = new DateTime('09:30:00');
$addSeconds->add(new DateInterval('PT30S'));
echo "Given time plus 30 seconds = ". $addSeconds->format('l, H:i:sa');

$addMin = new DateTime('22:30:00');
$addMin->add(new DateInterval('PT50M'));
echo "<br> Given time plus 30 minutes = ". $addMin->format('l, H:i:sa');

$addHours = new DateTime('06:30:00');
$addHours->add(new DateInterval('PT2H'));
echo "<br> Given time plus 2 hours = ". $addHours->format('l, H:i:sa');

The code above should return the following:

Given time plus 30 seconds = Tuesday, 09:30:30am
Given time plus 30 minutes = Tuesday, 23:20:00pm
Given time plus 2 hours = Tuesday, 08:30:00am

Another way to do the above operation is by using the modify function:

$addSeconds = new DateTime('09:30:00');
$addSeconds->modify('+30 seconds');
echo "Given time plus 30 seconds = ". $addSeconds->format('l, H:i:sa');

$addMin = new DateTime('22:30:00');
$addMin->modify('+30 minutes    ');
echo "<br> Given time plus 30 minutes = ". $addMin->format('l, H:i:sa');

$addHours = new DateTime('06:30:00');
$addHours->modify('+2 hours');
echo "<br> Given time plus 2 hours = ". $addHours->format('l, H:i:sa');

The code above will return the same result as the previous one.

Subtracting from times in PHP

Subtracting dates is the same process as adding times but with a sub function instead of the add function. Here's an example:

$minusSeconds = new DateTime('09:30:00');
$minusSeconds->sub(new DateInterval('PT90S'));
echo "Given time minus 90 seconds = ". $minusSeconds->format('l, H:i:sa');

$minusMin = new DateTime('22:30:00');
$minusMin->sub(new DateInterval('PT40M'));
echo "<br> Given time minus 40 minutes = ". $minusMin->format('l, H:i:sa');

$minusHours = new DateTime('06:30:00');
$minusHours->sub(new DateInterval('PT15H'));
echo "<br> Given time minus 15 hours = ". $minusHours->format('l, H:i:sa');

The code above subtracts 90 seconds, 40 minutes, and 15 hours, respectively, from the given dates and returns the following result:

Given time minus 90 seconds = Wednesday, 09:28:30am
Given time minus 40 minutes = Wednesday, 21:50:00pm
Given time minus 15 hours = Tuesday, 15:30:00pm

Here's how to achieve the same result using the modify function:

$minusSeconds = new DateTime('09:30:00');
$minusSeconds->modify('-90 seconds');
echo "Given time minus 90 seconds = ". $minusSeconds->format('l, H:i:sa');

$minusMin = new DateTime('22:30:00');
$minusMin->modify('-40 minutes');
echo "<br> Given time minus 40 minutes = ". $minusMin->format('l, H:i:sa');

$minusHours = new DateTime('06:30:00');
$minusHours->modify('-15 hours');
echo "<br> Given time minus 15 hours = ". $minusHours->format('l, H:i:sa');

The code above will return the same result as the previous one.

Working with time intervals in PHP

Checking the intervals between two times in PHP is easy with the diff function. For example, you can check the seconds, minutes, and hours between two different times in PHP:

$time1 = new DateTime('06:30:00');
$time2 = new DateTime('10:15:45');
$interval = $time1->diff($time2);
$seconds = $interval->h * 3600 + $interval->i * 60 + $interval->s . " seconds <br>";
$minutes = $interval->h * 60 + $interval->i . " minutes <br>";
$hours = $interval->h . " hours <br>";
echo $seconds;
echo $minutes; 
echo $hours;

The code above should return the following result:

13545 seconds
225 minutes
3 hours

Handling timezones in PHP

PHP provides a DateTimeZone class that enables you to work with timezones easily in your applications. For example, to display the current times in different timezones, you can use the DateTimeZone class:

$ny = new DateTime('now', new DateTimeZone('America/New_York'));
$lg = new DateTime('now', new DateTimeZone('Africa/Lagos'));
$ca = new DateTime('now', new DateTimeZone('Africa/Ouagadougou'));
$rs = new DateTime('now', new DateTimeZone('Europe/Moscow'));
echo "Current time in New York: " . $ny->format('l, Y-m-d H:i:s') . "<br>";
echo "Current time in Lagos: " . $lg->format('l, Y-m-d H:i:s') . "<br>";
echo "Current time in Ouagadougou: " . $ca->format('l, Y-m-d H:i:s') . "<br>";
echo "Current time in Moscow: " . $rs->format('l, Y-m-d H:i:s') . "<br>";

The code above will return the following:

Current time in New York: Wednesday, 2023-09-13 09:29:37
Current time in Lagos: Wednesday, 2023-09-13 14:29:37
Current time in Ouagadougou: Wednesday, 2023-09-13 13:29:37
Current time in Moscow: Wednesday, 2023-09-13 16:29:37

Note: The results above will change depending on when the code is run.

Find the time difference between two timezones

Another common use case when working with timezones is checking the difference between two timezones. Here's an example of how to do this in PHP:

$ny = new DateTime('14:30:00', new DateTimeZone('America/New_York'));
$ln = new DateTime('14:30:00', new DateTimeZone('Europe/London'));

$diff = $ny->diff($ln);

echo $diff->format('The difference between the given times is %R%H hours %I minutes');

The code above defines a particular time for New York and London and checks their difference. The code above should return the following:

The difference between the given times is -05 hours 00 minutes

Listing all the supported timezones in PHP

PHP provides access to the full list of the supported timezones via the DateTimeZone class. For example, you can print out all the available timezones in your application like this:

$no = 1;
$timeZones = DateTimeZone::listIdentifiers();
foreach ($timeZones as $tz) {
    echo $no++ . ". ";  
    echo $tz . "<br>";
}

The code above will return the complete list of 419 timezones built into PHP.

In the next section, let's explore some common date and time operations in PHP.

Common date and time tasks in PHP

Adding days, weeks, months, and years to dates

You can add days, weeks, months, and years to dates in PHP using the modify function:

$date = new DateTime('now');
$date->modify('+4 years +1 day +2 week +3 month');
echo $date->format('Y-m-d') . "<br> <br>";

The code above will add 4 years, 3 months, 2 weeks, and 1 day to the current system time.

You can do the same with the DateTimeInterval class:

$date = new DateTime('now');
$date->add(new DateInterval('P4Y3M2W1D')); 
echo $date->format('Y-m-d') . "<br> <br>";

Note: The order doesn't matter in the first code example but is important in the second. Also, the opposite can be done using the - sign and sub method, respectively.

Subtracting seconds, minutes, and hours from times in PHP

You can subtract days, weeks, months, and years to dates at once in PHP using the sub-function and theDateTimeInterval` class:

$date = new DateTime('12:00:00');
$date->sub(new DateInterval('PT7H30M15S')); 
echo $date->format('H:i:s') . "<br> <br>";

The code above should subtract 7 hours, 30 minutes, and 15 seconds from the given time and return the following:

04:29:45

You can do the same with the modify function:

$date = new DateTime('12:00:00');
$date->modify('-7 hours -30 minutes -15 seconds'); 
echo $date->format('H:i:s') . "<br> <br>";

Note: The order is critical in the first code example, but it doesn't matter in the second one. Also, the opposite can be done by using the add method and the + sign, respectively.

Formatting relative times

You can easily format dates with "...ago" in PHP:

$date = new DateTime('2023-05-13 14:00:00');
$fewDaysAgo = new DateTime('2023-05-09 11:00:00');
$diff = date_diff($fewDaysAgo, $date);
echo $diff->format('%R%a days %h hours ago); 

The code above will return the following:

+4 days 3 hours ago

Calculating the time it takes for code to run

Calculating the time it takes for a block of code to run in PHP is done using the hrtime function. Here's an example:

$start_time = hrtime(true);

for ($i = 0; $i < 1000000; $i++) {

}

$end_time = hrtime(true);

$elapsed_time = $end_time - $start_time;

$elapsed_time_seconds = $elapsed_time / 1e9;

echo "Elapsed time: {$elapsed_time_seconds} seconds";

The code above records the start time using the hrtime function, defines an empty that runs 100,000 times, and records the end time. Finally, it will calculate the elapsed time in nanoseconds, convert it to seconds, and print it out.

Conclusion

That is it! You are ready to start building amazing date and time features in your PHP applications.

In this article, you’ve learned everything you need to know about dates and times in PHP, including parsing dates, manipulating dates, calculating intervals and differences, performing arithmetic operations on times, working with timezones, and much more.

Get the Honeybadger newsletter

Each month we share news, best practices, and stories from the DevOps & monitoring community—exclusively for developers like you.
    author photo
    Adebayo Adams

    Being a self taught developer himself, Adams understands that consistent learning and doing is the way to become self sufficient as a software developer. He loves learning new things and firmly believes that learning never stops.

    More articles by Adebayo Adams
    An advertisement for Honeybadger that reads 'Turn your logs into events.'

    "Splunk-like querying without having to sell my kidneys? nice"

    That’s a direct quote from someone who just saw Honeybadger Insights. It’s a bit like Papertrail or DataDog—but with just the good parts and a reasonable price tag.

    Best of all, Insights logging is available on our free tier as part of a comprehensive monitoring suite including error tracking, uptime monitoring, status pages, and more.

    Start logging for FREE
    Simple 5-minute setup — No credit card required