How to Add 24 Hours to a Unix Timestamp in PHP?

In PHP, you may encounter scenarios where you need to add a specific amount of time, such as 24 hours, to a Unix timestamp.

This is common when you want to calculate a future date and time based on a given timestamp. In this article, we'll explore how to add 24 hours to a Unix timestamp in PHP.

To add 24 hours to a Unix timestamp in PHP, you can follow these steps:

  1. Obtain the original Unix timestamp.
  2. Use the strtotime() function or the DateTime class to create a new timestamp representing the added time.
  3. Display the new timestamp or format it as a human-readable date and time.

Let's look at both methods:

1. Using "strtotime()" function

The strtotime() function is a simple and straightforward way to add hours to a Unix timestamp. You can pass a date string with the additional hours to the function, and it will return a new timestamp. Here's an example of adding 24 hours to a Unix timestamp:

$originalTimestamp = time(); // Current Unix timestamp
$addedHours = 24;
$newTimestamp = strtotime("+$addedHours hours", $originalTimestamp);

echo "Original Timestamp: $originalTimestamp\n";
echo "New Timestamp: $newTimestamp";

In this code:

This method allows you to easily add hours to a timestamp, making it a useful choice for simple calculations.


2. Using the "DateTime" Class

The DateTime class in PHP provides a more versatile and object-oriented approach for date and time manipulation.

You can create a DateTime object from the original timestamp and then use the add() method to add hours. Here's an example:

$originalTimestamp = time(); // Current Unix timestamp
$addedHours = 24;
$dateTime = new DateTime("@$originalTimestamp");
$dateTime->add(new DateInterval("PT{$addedHours}H"));

$newTimestamp = $dateTime->getTimestamp();

echo "Original Timestamp: $originalTimestamp\n";
echo "New Timestamp: $newTimestamp";

In this code:

The DateTime class offers more control and flexibility for date and time operations and is a preferred choice for more complex tasks.


Conclusion

Adding hours to a Unix timestamp in PHP is a common operation when working with date and time data. You can choose between the strtotime() function for simplicity and the DateTime class for more advanced date manipulation. Select the method that best suits your specific requirements and the complexity of your task.