Subtract time (hours, minutes, and seconds) from date can be easily done using the date() and strtotime() function in PHP. The date() function formats a local date and time, and returns a formatted string. On the other hand, the strtotime() function converts string formatted DateTime into Unix timestamp. You can use these two functions together to subtract time form the current date using PHP.
The following example code helps you to subtract time from current DateTime or a specific date-time.
Subtract Hours from Datetime
Use the following code snippet to subtract 2 hours from current date and time using PHP.
// Current date and time
$datetime = date("Y-m-d H:i:s");
// Convert datetime to Unix timestamp
$timestamp = strtotime($datetime);
// Subtract time from datetime
$time = $timestamp - (2 * 60 * 60);
// Date and time after subtraction
$datetime = date("Y-m-d H:i:s", $time);
Subtract Minutes from Datetime
Use the following code snippet to subtract 5 minutes from current date and time using PHP.
// Current date and time
$datetime = date("Y-m-d H:i:s");
// Convert datetime to Unix timestamp
$timestamp = strtotime($datetime);
// Subtract time from datetime
$time = $timestamp - (5 * 60);
// Date and time after subtraction
$datetime = date("Y-m-d H:i:s", $time);
Subtract Seconds from Datetime
Use the following code snippet to subtract 30 seconds from current date and time using PHP.
<?php
// Current date and time
$datetime = date("Y-m-d H:i:s");
// Convert datetime to Unix timestamp
$timestamp = strtotime($datetime);
// Subtract time from datetime
$time = $timestamp - 30;
// Date and time after subtraction
$datetime = date("Y-m-d H:i:s", $time);
How do I subtract two strtotime() values and add its result to another strtotime() value to get my desired time value in Y:m:d H:i:s format?