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>
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>
This is a more concise way of achieving the same result.
Additional Notes:
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!