Add hours onto a date and time using PHP.

This is a tutorial on how to add hours onto a date and time using PHP. In this guide, I will provide examples using both the regular date and time functions, as well as PHP’s DateTime object.

Adding hours onto a date and time using PHP’s date and time functions.

Take a look at the following example, which is intentionally verbose:

In the PHP code above, we:

  • Got the current Unix timestamp using PHP’s time function.
  • Defined a variable called $hoursToAdd, which contains the number of hours that we want to add onto our date and time. In this case, we will be adding 2 hours onto the current time. If we wanted to add 12 hours onto the current time, then we would simply change this variable to 12.
  • We then converted our hours into seconds by multiplying the amount of hours by 3600 (60 x 60 = 3600). This works because there are 3600 seconds in one hour. In the case above, 2 is multiplied by 3600, which gives us 7200. This is correct, as there are 7200 seconds in two hours.
  • We then added these seconds onto the current timestamp.
  • Finally, we printed out the new date and time using PHP’s date function.

When I ran the code above, I received the following result:

2 hour(s) added onto 03/01/20 14:10 becomes 03/01/20 16:10

Perfect!

Adding hours onto a date and time using PHP’s DateTime object.

If you want to use the DateTime object for this operation, then you can use the following example:

As you can see, you do not need to do any multiplication sums while using the DateTime object, as it comes equipped with a handy method called DateTime::add. In the code above, we simply passed a DateInterval object into this method. Our DateInterval object had PT2H set as the $interval_spec parameter, which basically translates into “a period of two hours.”

Other examples of what you could pass into the constructor of the DateInterval object:

  • PT1H: A period of one hour.
  • PT6H: A period of six hours.
  • PT24H: A period of 24 hours.

The most important thing in this case is that we use the letter “H” as the Period Designator.

Hopefully, this post helped you to solve your issue!

Related tutorials:

Facebook Comments