Home > Backend Development > PHP Tutorial > How to Add Hours to a PHP Timestamp?

How to Add Hours to a PHP Timestamp?

Patricia Arquette
Release: 2024-11-04 09:11:30
Original
979 people have browsed it

How to Add Hours to a PHP Timestamp?

Adding Hours to a PHP Date

In PHP, you can easily retrieve the current date and time using the date() function. However, if you need to modify this timestamp to add a specific number of hours, you can use the strtotime() function.

Original Request:

The user requests a way to add a specified number of hours to the current timestamp, stored in the variable $now. The hours range from 24 to 800.

Solution:

To add a specific number of hours to $now, you can use strtotime() as follows:

<code class="php">$new_time = date("Y-m-d H:i:s", strtotime("+$hours hours", strtotime($now)));</code>
Copy after login

This will create a new $new_time variable that represents the updated timestamp with the added hours.

Alternative Syntax:

In the provided solution, we use the sprintf() function to combine the hours variable with the string. However, you can also use the following syntax:

<code class="php">$new_time = date("Y-m-d H:i:s", strtotime("+" . $hours . " hours", strtotime($now)));</code>
Copy after login

This is a more concise way of achieving the same result.

Additional Notes:

  • The examples assume that $now is a valid date string in the "Y-m-d H:i:s" format. If it is in a different format, you will need to use strtotime() to convert it first.
  • You can adjust the format string in date() to output the date and time in any desired format.

The above is the detailed content of How to Add Hours to a PHP Timestamp?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template