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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2382458/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 06:15:02  来源:igfitidea点击:

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

phpdatetimedatetimetimestamp

提问by vitto

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?

有没有可能做类似的事情?这种功能可以工作多年,但如何对其他时间类型做同样的事情?

回答by AlexV

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...

像这样的东西会在几个小时和几天内运行良好(使用 86400 几天),但对于几个月和一年来说,它有点棘手......

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

回答by Phil Rykoff

Try to use datetime::sub

尝试使用 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';

?>

回答by GSto

something like this:

像这样:

function offset hours($hours) {
    return strtotime("+$hours hours");
}