PHP script to subtract or deduct time. Tutorial with code and example
March 23, 2008
Often we need to subtract years, months, days, hours, minutes and even seconds from current time or any other time. Previously I wrote a script and/or tutorial on how to add time. This script is nothing but a little modified version of the previous script to deduct or subtract time. I wrote this script since several people often come to search the time adding script. So, I wrote this script to check if this is helpful for any one.
Okay. Here is the PHP function to subtract or decuct time.
function subtractTime($hours=0, $minutes=0, $seconds=0, $months=0, $days=0, $years=0)
$totalHours = date(“H”) – $hours;
$totalMinutes = date(“i”) – $minutes;
$totalSeconds = date(“s”) – $seconds;
$totalMonths = date(“m”) – $months;
$totalDays = date(“d”) – $days;
$totalYears = date(“Y”) – $years;
$timeStamp = mktime($totalHours, $totalMinutes, $totalSeconds, $totalMonths, $totalDays, $totalYears);
$myTime = date(“Y-m-d H:i:s A”, $timeStamp);
Now we call the function to test the output.
// Let us first see the current time
echo ‘Current Time: ‘ . date(“Y-m-d H:i:s A”);
// Now let us deduct 5 hours, 2 days and 1 year from now
echo ‘New Time: ‘ . subtractTime(5,0,0,0,2,1);
And here is a sample output:
Current Time: 2008-03-23 21:40:28 PM
New Time: 2007-03-21 16:40:28 PM
Thus, you can subtract or deduct time (such as second, minute, hour, day, month, year) easily with a simple function.