PASSWORD RESET

Your destination for complete Tech news

PHP

How to add hours in date time in PHP?

880 0
< 1 min read

To add hours to a datetime in PHP, you can use the DateTime class along with the DateInterval class. Here’s an example code snippet:

$datetime = new DateTime('2023-02-25 10:30:00'); // the datetime you want to add hours to
$hours_to_add = 2; // the number of hours to add

$datetime->add(new DateInterval('PT' . $hours_to_add . 'H'));

echo $datetime->format('Y-m-d H:i:s');

In this example, we’re starting with a datetime of ‘2023-02-25 10:30:00’ and adding 2 hours to it. The DateTime object is created using the initial datetime string.

The add() method is then called on the DateTime object with a new instance of the DateInterval class passed as an argument. The DateInterval object is constructed using the ‘PT’ format specifier for a time period, followed by the number of hours to add, and the ‘H’ format specifier for hours.

Finally, the format() method is called on the DateTime object to format the resulting datetime string in the ‘Y-m-d H:i:s’ format, which represents year, month, day, hours, minutes, and seconds.

The output of the example code snippet will be ‘2023-02-25 12:30:00’, which is the original datetime with 2 hours added to it.

Leave A Reply

Your email address will not be published.

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