Add Hours to Date with PHP
To manipulate dates and times in PHP, you can utilize the date(), strtotime(), and sprintf() functions. Here's how you can add a number of hours to the current date/time:
<code class="php"><?php // Get the current date/time $now = date("Y-m-d H:m:s"); // Define the number of hours to add $hours = 24; // Use strtotime() to calculate the new time $new_time = date("Y-m-d H:i:s", strtotime("+$hours hours")); // You can also specify the number of hours dynamically using variables or constants $new_time = date("Y-m-d H:i:s", strtotime(sprintf("+%d hours", $hours))); // Output the new time echo $new_time; ?></code>
This code demonstrates how to add the specified number of hours to the current date/time and store it in the $new_time variable. The strtotime() function calculates the timestamp (seconds since the Unix epoch) based on the provided string representing a time period (in this case, " " followed by the number of hours and "hours").
By using sprintf() to dynamically format the number of hours, you gain the flexibility to pass in different values at runtime. Note that if you need to include variables within the strtotime() string, you must use double quotes (") and variable placeholders, as shown in the code. Also, the date() function formats the resulting timestamp into a human-readable date and time string.
The above is the detailed content of How to Add Hours to a Date in PHP?. For more information, please follow other related articles on the PHP Chinese website!