日期格式的 php 字符串,添加 12 小时
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15228832/
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
php string in a date format, add 12 hours
提问by CQM
I have this stringobject in my php array
string我的 php 数组中有这个对象
"2013-03-05 00:00:00+00"
“2013-03-05 00:00:00+00”
I would like to add 12 hours to the entry within PHP, then save it back to string in the same format
我想在 PHP 中的条目中添加 12 小时,然后以相同的格式将其保存回字符串
I believe this involves converting the string to a date object. But I'm not sure how smart the date object is and if I need to tell it formatting parameters or if it is supposed to just take the string
我相信这涉及将字符串转换为日期对象。但我不确定日期对象有多聪明,是否需要告诉它格式化参数或者它是否应该只接受字符串
$date = new DateTime("2013-03-05 00:00:00+00");
$date->add("+12 hours");
//then convert back to string or just assign it to a variable within the array node
I was getting back empty values from this method or a similar one I tried
我正在从这种方法或我尝试过的类似方法中取回空值
How would you solve this issue?
你会如何解决这个问题?
Thanks, your insight is appreciated
谢谢,感谢您的洞察力
回答by John Conde
Change add()to modify(). add()expects a DateInterval object.
更改add()为modify()。add()需要一个 DateInterval 对象。
<?php
$date = new DateTime("2013-03-05 00:00:00+00");
$date->modify("+12 hours");
echo $date->format("Y-m-d H:i:sO");
Here's an example using a DateInterval object:
下面是一个使用 DateInterval 对象的示例:
<?php
$date = new DateTime("2013-03-05 00:00:00+00");
$date->add(new DateInterval('PT12H'));
echo $date->format("Y-m-d H:i:sO");
回答by Davide Berra
Change this line
改变这一行
$date->add("+12 hours");
with
和
$date->add(new DateInterval("PT12H"));
this will add 12 hours to your date
这将为您的约会增加 12 小时
Look at the DateInterval constructorpage to know how to build the DateIntervalstring
查看DateInterval 构造函数页面以了解如何构建DateInterval字符串
回答by Gayan Fernando
Use this to add hours,
用它来增加小时数,
$date1= "2014-07-03 11:00:00";
$new_date= date("Y-m-d H:i:s", strtotime($date1 . " +3 hours"));
echo $new_date;
回答by Valentina Ungurean
If you have dynamic interval, this way will avoid errors of wrong format for $dateDiff:
如果您有动态间隔,这种方式将避免 $dateDiff 格式错误的错误:
$dateDiff = "12 hours";
$interval = DateInterval::createFromDateString($dateDiff);
$date = new DateTime("2013-03-05 00:00:00+00");
$date->add($interval);
echo $date->format("Y-m-d H:i:sO");

