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

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));

Leave a Comment