简体   繁体   English

大于 24 到 DateTime 的字符串日期

[英]string date greater than 24 to DateTime

In PHP, how can I convert string time such as "84:12:49" (hours greater than 24) to DateTime object?在 PHP 中,如何将字符串时间如“84:12:49”(大于 24 小时)转换为 DateTime object? I tried convert it to unix first but it doesn't return proper value我尝试先将其转换为 unix 但它没有返回正确的值

$time = explode(":", $time);
$timeUnix = mktime(intval($time[0]),intval($time[1]), intval($time[2]));

You want to get a DateInterval object.你想得到一个DateInterval object。 You could be use ->diff() with two DateTime objects.您可以将->diff()与两个 DateTime 对象一起使用。

$time = '84:12:49';
[$hours, $minutes, $seconds] = explode(':', $time);
$totalSeconds = $seconds + $minutes*60 + $hours*3600;

$interval = (new DateTime())->diff(DateTime::createFromFormat('U', time() + $totalSeconds));
var_dump($interval);

Output Output

object(DateInterval)#3 (16) {
  ["y"]=>  int(0)
  ["m"]=>  int(0)
  ["d"]=>  int(3)
  ["h"]=>  int(12)
  ["i"]=>  int(12)
  ["s"]=>  int(48)
  ["f"]=>  float(0.996002)
  ["weekday"]=>  int(0)
  ["weekday_behavior"]=>  int(0)
  ["first_last_day_of"]=>  int(0)
  ["invert"]=>  int(0)
  ["days"]=>  int(3)
  ["special_type"]=>  int(0)
  ["special_amount"]=>  int(0)
  ["have_weekday_relative"]=>  int(0)
  ["have_special_relative"]=>  int(0)
}

Demo (3v4l.org)演示 (3v4l.org)

Use DateInterval like so...像这样使用 DateInterval ...

<?php

$time = '84:12:49';
$timeArray = explode(":", $time);

$date = new DateTime();
$date->add(new DateInterval('PT' . $timeArray[0] . 'H' . $timeArray[1] .  'M' . $timeArray[2] . 'S'));
// Your DateTime object is $date, display it like so for example...
echo $date->format('Y-m-d H:i:s');

We are creating a new DateTime object starting now.从现在开始,我们正在创建一个新的DateTime object。

We are then using DateInterval to add a new time period (PT) (starting from now) with the provided hours, minutes and seconds.然后,我们使用DateInterval添加一个新的时间段 (PT)(从现在开始),其中包含提供的小时、分钟和秒。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM