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

后端 未结 3 1661
Happy的楠姐
Happy的楠姐 2020-12-03 05:49

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 we

相关标签:
3条回答
  • 2020-12-03 06:17

    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));
    
    0 讨论(0)
  • 2020-12-03 06:25

    something like this:

    function offset hours($hours) {
        return strtotime("+$hours hours");
    }
    
    0 讨论(0)
  • 2020-12-03 06:37

    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';
    
    ?>
    
    0 讨论(0)
提交回复
热议问题