Subtracting a certain number of hours, days, months or years from date

44,235

Solution 1

For hours:

function get_offset_hours($hours)
{
    return date('Y-m-d H:i:s', time() + 3600 * $hours);
}

Something like that will work well for hours and days (use 86400 for days), but for months and year it's a bit trickier...

Also you can also do it this way:

$date = strtotime(date('Y-m-d H:i:s') . ' +1 day');
$date = strtotime(date('Y-m-d H:i:s') . ' +1 week');
$date = strtotime(date('Y-m-d H:i:s') . ' +2 weeks');
$date = strtotime(date('Y-m-d H:i:s') . ' +1 month');
$date = strtotime(date('Y-m-d H:i:s') . ' +30 days');
$date = strtotime(date('Y-m-d H:i:s') . ' +1 year');

echo(date('Y-m-d H:i:s', $date));

Solution 2

Try to use datetime::sub

Example from the docs (linked):

<?php

$date = new DateTime("18-July-2008 16:30:30");
echo $date->format("d-m-Y H:i:s").'<br />';

date_sub($date, new DateInterval("P5D"));
echo '<br />'.$date->format("d-m-Y").' : 5 Days';

date_sub($date, new DateInterval("P5Y5M5D"));
echo '<br />'.$date->format("d-m-Y").' : 5 Days, 5 Months, 5 Years';

date_sub($date, new DateInterval("P5YT5H"));
echo '<br />'.$date->format("d-m-Y H:i:s").' : 5 Years, 5 Hours';

?>
Share:
44,235
vitto
Author by

vitto

I'm a UX/UI developer, located in Italy

Updated on July 05, 2022

Comments

  • vitto
    vitto almost 2 years

    I'm trying to create a simple function which returns me a date with a certain number of subtracted days from now, so something like this but I dont know the date classes well:

    <?
    function get_offset_hours ($hours) {
        return date ("Y-m-d H:i:s", strtotime (date ("Y-m-d H:i:s") /*and now?*/));
    }
    
    function get_offset_days ($days) {
        return date ("Y-m-d H:i:s", strtotime (date ("Y-m-d H:i:s") /*and now?*/));
    }
    
    function get_offset_months ($months) {
        return date ("Y-m-d H:i:s", strtotime (date ("Y-m-d H:i:s") /*and now?*/));
    }
    
    function get_offset_years ($years) {
        return date ("Y-m-d H:i:s", strtotime (date ("Y-m-d H:i:s") + $years));
    }
    
    print get_offset_years (-30);
    ?>
    

    Is it possible to do something similar to this? this kind of function works for years, but how to do the same with other time types?

  • thetaiko
    thetaiko about 14 years
    If these don't work for you its because they are new in PHP5.3
  • vitto
    vitto about 14 years
    unfortunately, I have 5.2.xx version, but I'll remember it!