从日期减去一定数量的小时,天,月或年 [英] 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?
推荐答案
:
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));
这篇关于从日期减去一定数量的小时,天,月或年的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文