Current Location: Home> Latest Articles> gmdate and strtotime deal with date addition and subtraction

gmdate and strtotime deal with date addition and subtraction

gitbox 2025-05-26

Example: Use gmdate() and strtotime() to add and subtract dates

 <?php
// Set the base date
$baseDate = "2025-05-24 12:00:00";

// Convert to timestamp(UTC)
$timestamp = strtotime($baseDate);

// Date plus1sky
$addOneDay = gmdate("Y-m-d H:i:s", strtotime("+1 day", $timestamp));

// Date reduction2Hour
$subtractTwoHours = gmdate("Y-m-d H:i:s", strtotime("-2 hours", $timestamp));

// Output result
echo "Base date(UTC): " . gmdate("Y-m-d H:i:s", $timestamp) . "\n";
echo "add1sky后: " . $addOneDay . "\n";
echo "reduce2Hour后: " . $subtractTwoHours . "\n";
?>

Run the above code and the output results are roughly as follows:

 Base date(UTC): 2025-05-24 12:00:00
add1sky后: 2025-05-25 12:00:00
reduce2Hour后: 2025-05-24 10:00:00

explain

  • strtotime("+1 day", $timestamp) : Add one day (24 hours) to the base time stamp.

  • strtotime("-2 hours", $timestamp) : Reduce two hours on the basis of the benchmark timestamp.

  • gmdate() is responsible for formatting the timestamps into strings and ensuring that the time is UTC time.

Practical application scenarios

  • In scenarios where different time zones need to be processed but require unified time output, such as cross-border server time synchronization.

  • Use addition and subtraction of timestamps in the database to ensure that the displayed time is a unified standard time.

  • Generate cache expiration time or countdown time point, etc.