1

我收到了两个日期时间字符串。

$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');

继续思考应该有一些更容易转换这些字符串而不是每次都解析的东西。而且,这是我的问题。我怎样才能更容易地做到这一点?

4

2 回答 2

1

按照jeroen的建议使用DateTime::createFromFormat使其非常简单:-

$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
于 2013-04-14T19:39:57.917 回答
0

您不需要任何日期时间解析,因为您的输入格式是标准 SOAP 格式。

你可以这样做:

$d1 = new DateTime('2012-12-25T23:00:43.29');

查看更多关于支持的格式。

于 2013-09-18T02:32:22.617 回答