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));
这篇关于从日期中减去一定数量的小时、天、月或年的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从日期中减去一定数量的小时、天、月或年


- 带有通配符的 Laravel 验证器 2021-01-01
- Mod使用GET变量将子域重写为PHP 2021-01-01
- Laravel 仓库 2022-01-01
- SoapClient 设置自定义 HTTP Header 2021-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- 如何定位 php.ini 文件 (xampp) 2022-01-01
- 没有作曲家的 PSR4 自动加载 2022-01-01
- 正确分离 PHP 中的逻辑/样式 2021-01-01
- PHP Count 布尔数组中真值的数量 2021-01-01
- 从 PHP 中的输入表单获取日期 2022-01-01