18 November, 2010

Subtract hours from date in php

One of my friend asked me how to subtract hours from date in php. The subtraction
could be hours or days. So here is what i did for him, to subtract hours from date
in php.
Lets say we need to subtract two hours from current date, then

//get today's date
$today = date("Y-m-d H:i:s", time());
$hours = 2;
//first convert today's date to timestamp, as
$strTodayDate = strtotime($today);
//now subtract hours from date
$subtractedTimeStr = strtotime("- $hours hours", $strTodayDate);
//now get the resulting date, i.e. date prior to 2 hours from today
$finalDate = date("Y-m-d H:i:s", $subtractedTimeStr);
echo $finalDate;

And thats it. To subtract days from date use days in place of hours in above code as:

$days = 2;
$subtractedTimeStr = strtotime("- $days days", $strTodayDate);

Similarly, to add days or hours to date we can do as:

$subtractedTimeStr = strtotime("+ $hours hours", $strTodayDate);
$subtractedTimeStr = strtotime("+ $days days", $strTodayDate);

Hope this helps someone.

No comments: