从日期减去一定数量的小时、天、月或年

2022-01-13 00:00:00 datetime time timestamp date php

我正在尝试创建一个简单的函数,它返回一个从现在开始减去一定天数的日期,所以像这样,但我不太了解日期类:

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?

推荐答案

几个小时:

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

类似的东西在几个小时和几天内都可以正常工作(几天使用 86400),但是对于几个月和一年来说,它有点棘手......

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

你也可以这样做:

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

相关文章