PHP,需要从 DateTime 中减去 12 小时 30 分钟

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5768846/
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 22:25:49  来源:igfitidea点击:

PHP, need to subtract 12 hours and 30 minutes from a DateTime

phpdatetimedate

提问by gourav

I have a PHP DateTimevariable.

我有一个 PHPDateTime变量。

How can I reduce or subtract 12hours and 30 minutes from this date in at PHP runtime?

如何在 PHP 运行时从该日期减少或减去 12 小时 30 分钟?

回答by Rafe Kettler

Subtract 12 Hours and 30 minutes from a DateTime in PHP:

从 PHP 中的 DateTime 减去 12 小时 30 分钟:

$date = new DateTime();
$tosub = new DateInterval('PT12H30M');
$date->sub($tosub);

The P stands for Period. The T stands for Timespan.

P代表期间。T 代表时间跨度。

See DateTime, DateTime::sub, and DateIntervalin the PHP manual. You'll have to set the DateTimeto the appropriate date and time, of course.

请参阅PHP 手册中的DateTimeDateTime::subDateInterval。当然,您必须将 设置DateTime为适当的日期和时间。

回答by fitorec

Try with:

尝试:

$date = new DateTime('Sat, 30 Apr 2011 05:00:00 -0400');
echo $date->format('Y-m-d H:i:s') . "\n";
$date->sub(new DateInterval('PT12H30M'));
echo $date->format('Y-m-d H:i:s') . "\n";

//Result

//结果

2011-04-30 05:00:00
2011-04-29 16:30:00

回答by aexl

Try strtotime()function:

试用strtotime()功能:

$source_timestamp=strtotime("Sat, 30 Apr 2011 05:00:00 -0400");
$new_timestamp=strtotime("-12 hour 30 minute", $source_timestamp);
print date('r', $new_timestamp);

回答by kikuyu1

try using this instead

尝试改用这个

//set timezone
date_default_timezone_set('GMT');

//set an date and time to work with
$start = '2014-06-01 14:00:00';

//display the converted time
echo date('Y-m-d H:i',strtotime('+1 hour +20 minutes',strtotime($start)));

回答by Mohamed23gharbi

If you are not so familiar with the spec of DateInterval like PT12H30M you can proceed with more human readable way using DateInterval::createFromDateString as follows :

如果您不太熟悉像 PT12H30M 这样的 DateInterval 规范,您可以使用 DateInterval::createFromDateString 以更易于阅读的方式进行,如下所示:

$date = new DateTime();
$interval = DateInterval::createFromDateString('12 hour 30 minute');
$date->sub($interval);

Or with direct interval in sub function like below :

或者在子函数中使用直接间隔,如下所示:

$date = new DateTime();
$date->sub(DateInterval::createFromDateString('12 hour 30 minute'));

回答by ChrisWue

Store it in a DateTimeobject and then use the DateTime::submethod to subtract the timespan.

将其存储在一个DateTime对象中,然后使用该DateTime::sub方法减去时间跨度。

回答by devmyb

Using simply strtotime

使用简单 strtotime

echo date("Y-m-d H:i:s",strtotime("-12 hour -30 minutes"));

Using DateTimeclass

使用DateTime

$date = new DateTime("-12 hour -30 minutes");
echo $date->format("Y-m-d H:i:s");