php字符串以日期格式添加12小时 [英] php string in a date format, add 12 hours

查看:382
本文介绍了php字符串以日期格式添加12小时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的php数组中有这个 string 对象



2013-03-05 00:00: 00 + 00



我想在PHP中添加12个小时,然后以相同的格式将其保存回到字符串



我相信这涉及将字符串转换为日期对象。但我不知道日期对象是多么聪明,如果我需要告诉它格式参数,或者它应该只是采取字符串

  $ date = new DateTime(2013-03-05 00:00:00 + 00); 
$ date-> add(+ 12小时);
//然后转换回字符串或只是将其分配给数组节点中的变量

我正在从这种方法或类似的方法获取空值我尝试



您将如何解决这个问题?



谢谢,您的洞察力被赞赏

解决方案

更改 add() modify() add()期望一个DateInterval对象。

 <?php 
$ date = new DateTime(2013-03-05 00:00:00 + 00);
$ date-> modify(+ 12小时);
echo $ date-> format(Y-m-d H:i:sO);

参见它在行动



以下是使用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);

查看它在行动


I have this string object in my php array

"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

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

解决方案

Change add() to modify(). add() expects a DateInterval object.

<?php
$date = new DateTime("2013-03-05 00:00:00+00");
$date->modify("+12 hours");
echo $date->format("Y-m-d H:i:sO");

See it in action

Here's an example using a DateInterval object:

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

See it in action

这篇关于php字符串以日期格式添加12小时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆