从日期中减去一定数量的小时、天、月或年
我正在尝试创建一个简单的函数,它返回一个从现在开始减去一定天数的日期,所以类似这样的事情,但我不太了解日期类:
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));
相关文章