php 如何在此日期时间字符串的时间上添加一个小时?

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

How to add an hour onto the time of this datetime string?

php

提问by Hard worker

Here's an example of the datetime strings I am working with:

这是我正在使用的日期时间字符串的示例:

Tue May 15 10:14:30 +0000 2012

Here is my attempt to add an hour onto it:

这是我尝试在上面增加一个小时的尝试:

$time = 'Tue May 15 10:14:30 +0000 2012';
$dt = new DateTime($time);
$dt->add(new DateInterval('P1h'));

But the second line gives the error that it couldn't be converted.

但是第二行给出了无法转换的错误。

Thanks.

谢谢。

回答by Jon

You should add a Tbefore the time specification part:

您应该T在时间规范部分之前添加一个:

$time = 'Tue May 15 10:14:30 +0000 2012';
$dt = new DateTime($time);
$dt->add(new DateInterval('PT1H'));

See the DateIntervalconstructordocumentation:

请参阅DateInterval构造函数文档:

The format starts with the letter P, for "period." Each duration period is represented by an integer value followed by a period designator. If the duration contains time elements, that portion of the specification is preceded by the letter T.

格式以字母 P 开头,表示“句点”。每个持续时间段由一个整数值表示,后跟一个时间段指示符。如果持续时间包含时间元素,则规范的该部分前面有字母 T

(Emphasis added)

(强调)

回答by Marino Linaje

Previous answers work. However, I usually use datetime modify in my externally hosted websites. Check php manualfor more information. With the code proposed, it should work like this:

以前的答案有效。但是,我通常在外部托管的网站中使用日期时间修改。查看php 手册以获取更多信息。使用建议的代码,它应该像这样工作:

$time = 'Tue May 15 10:14:30 +0000 2012';
$dt = new DateTime($time);
$dt->modify('+ 1 hour');

For those not using object orientation, just use it this way (first line DateTime just to bring somethng new to this thread, I use it to check server time):

对于那些不使用面向对象的人,就这样使用它(第一行 DateTime 只是为了给这个线程带来一些新的东西,我用它来检查服务器时间):

$dt = new DateTime("@".$_SERVER['REQUEST_TIME']);  // convert UNIX epoch to PHP DateTime
$dt = date_modify($dt, "+1 hour");

Best,

最好的事物,

回答by lorenzo-s

Using strtotime():

使用strtotime()

$time = 'Tue May 15 10:14:30 +0000 2012';
$time = strtotime($time) + 3600; // Add 1 hour
$time = date('D M j G:i:s O Y', $time); // Back to string
echo $time;