【问题标题】:PHP convert time into a Time Period [closed]PHP将时间转换为时间段[关闭]
【发布时间】:2013-10-29 02:40:01
【问题描述】:

似乎有很多信息可以将时间段转换为时间,但反之则不然。

我需要做的一个例子是将 120 分钟转换为 P0DT2H0M0S。 13:10 进入 P0DT13H10M0S。 120 分钟进入 PT2H0M0S。

有什么快速简便的方法吗?

【问题讨论】:

  • 我会使用日期/时间函数。获取一个当前时间,用DateTime::modify()修改时间,然后用DateTime::diff()求出差异,就可以输出任意格式了。

标签: php string time intervals period


【解决方案1】:

我相信您所描述的格式是 ISO 8601 日期/时间格式。 Here's how it describes intervals.

DateInterval 类的 PHP 文档中,有人分享了一个示例,说明如何以面向对象的方式将字符串转换为 ISO 8601:

http://www.php.net/manual/en/class.dateinterval.php#113415

这是其他人的解决方案,使用函数式而不是面向对象的日期方法:

https://stackoverflow.com/a/13301472/2119660

【讨论】:

  • 欢呼。看起来我可以使用它。
【解决方案2】:

获取 ISO-8601 时间间隔持续时间的最简单方法是使用方法 createFromDateString

用途:

echo getISO8601duration_withZeros("3 year 20 day 15 minute"); # P3Y0M20DT0H15M0S
echo getISO8601duration_withZeros("1 hour 120 minutes");      # P0Y0M0DT1H120M0S
echo getISO8601duration_withZeros("7 year 5 month 3 day");    # P7Y5M3DT0H0M0S

# 13:10 example
$dt = new DateTime('13:10');
$interval_spec = "{$dt->format('H')} hour {$dt->format('i')} minute";
echo getISO8601duration_withZeros($interval_spec);            # P0Y0M0DT13H10M0S

功能:

function getISO8601duration_withZeros($interval_spec) {
    $interval = DateInterval::createFromDateString($interval_spec);
    return $interval->format('P%yY%mM%dDT%hH%iM%sS');
}

演示:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-31
    • 2014-08-30
    • 2013-04-23
    • 1970-01-01
    • 1970-01-01
    • 2013-06-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多