我正在发送两个日期时间字符串。
$StartDateTime = '2012-12-25T23:00:43.29';
$EndDateTime = '2012-12-26T06:50:43.29';
我需要执行timediff来产生已用时间,并将日期组件分配给一个列和时间组件到另一列。我在做的是:
$d1 = new DateTime();
$d2 = new DateTime();
list($year,$month,$day) = explode('-',mb_strstr($StartDateTime,'T', TRUE));
list($hour,$minute,$second) = explode(':',trim(mb_strstr($StartDateTime,'T', FALSE),'T'));
$d1->setDate($year,$month,$day);
$d1->setTime($hour,$minute,$second);
list($year,$month,$day) = explode('-',mb_strstr($EndDateTime,'T', TRUE));
list($hour,$minute,$second) = explode(':',trim(mb_strstr($EndDateTime,'T', FALSE),'T'));
$d2->setDate($year,$month,$day);
$d2->setTime($hour,$minute,$second);
$diff = $d1->diff($d2);
现在,我可以用我想要的任何格式获得$ diff:
$thisformat = $diff->format('%H:%I:%S');
$thatformat = $diff->format('%H%I%S');
而且,我可以将单独的DATE和TIME组件放入各自的对象属性(两个字符串)中:
$somedateproperty = $d1->format('Y-m-d');
$sometimeproperty = $d1->format('H:i:s');
$anotherdateproperty = $d2->format('Y-m-d');
$anothertimeproperty = $d2->format('H:i:s');
一直认为应该有更容易转换这些字符串的东西,而不是每次解析所有的字符串。而且,这是我的问题。我怎么能更容易地做到这一点?
答案 0 :(得分:1)
根据DateTime::createFromFormat的建议使用jeroen非常简单: -
$StartDateTime = \DateTime::createFromFormat("Y-m-d\TH:i:s.u", '2012-12-25T23:00:43.29');
$EndDateTime = \DateTime::createFromFormat("Y-m-d\TH:i:s.u", '2012-12-26T06:50:43.29');
var_dump($StartDateTime->diff($EndDateTime));
提供以下输出: -
object(DateInterval)[3]
public 'y' => int 0
public 'm' => int 0
public 'd' => int 0
public 'h' => int 7
public 'i' => int 50
public 's' => int 0
public 'invert' => int 0
public 'days' => int 0
答案 1 :(得分:0)
您不需要任何日期时间解析,因为您的输入格式是标准的SOAP格式。
你可以这样做:
$d1 = new DateTime('2012-12-25T23:00:43.29');