Subtract hours from a time and date using PHP.

This is a tutorial on how to subtract hours from a date and time using PHP. This can be useful if you need to work out an exact date and time in the recent past. For example: “What time was six hours ago?” or “What time was twelve hours ago?”

Subtracting hours using PHP’s time function.

You can subtract hours by using PHP’s time function and some basic arithmetic:

AnĀ  explanation of the PHP code above:

  1. We got the current Unix timestamp using PHP’s time function.
  2. We defined a variable called $hoursToSubtract. This variable contains the number of hours that we want to subtract from our date and time.
  3. After that, we converted our hours into seconds by multiplying them by 3600. This works because there are exactly 3600 seconds in one hour (60 x 60 = 3600). In the case above, 12 x 3600 = 43200.
  4. Finally, we subtracted those seconds from our timestamp and then printed out the result in a human friendly date format.

When I ran the example above at 14:52PM on the 9th of Jan, 2020, the output was:

09/01/20 02:52 was 12 hours ago.

As you can see, this is correct, as 12 hours before 14:52PM would have been 2:52AM.

Using PHP’s DateTime object to subtract hours from a date.

You can also use PHP’s DateTime object to subtract hours from a given date and time. Take the following example:

In the example above, we used the DateTime::sub method to subtract a period of 12 hours from the current timestamp. Essentially, we passed in a DateInterval object with PT12H as the $interval_spec parameter. PT12H basically means a “period of time of 12 hours.”

If you want to subtract hours from a given date, you could try the following:

If you test the DateTime example above, you will see that the output is: 2020-01-08 21:00

This is correct, as 2020-01-08 21:00 occurred exactly four hours before 2020-01-09 01:00.

Related tutorials:

Facebook Comments