我收到了两个日期时间字符串。
$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');
继续思考应该有一些更容易转换这些字符串而不是每次都解析的东西。而且,这是我的问题。我怎样才能更容易地做到这一点?