Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 491
vitto Avatar asked Mar 04 '10 20:03

vitto


2 Answers

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));
like image 102
AlexV Avatar answered Nov 13 '22 04:11

AlexV


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

?>
like image 35
Phil Rykoff Avatar answered Nov 13 '22 04:11

Phil Rykoff