如何将字符串持续时间转换为ISO 8601持续时间格式? (例如,“ 30分钟”到“ PT30M”) [英] How to convert string duration to ISO 8601 duration format? (e.g. "30 minutes" to "PT30M")

查看:565
本文介绍了如何将字符串持续时间转换为ISO 8601持续时间格式? (例如,“ 30分钟”到“ PT30M”)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有很多问题问如何用另一种方法(从这种格式转换转换为),但是我找不到如何在PHP中以ISO 8601持续时间格式输出的信息。

There are plenty of questions asking how to do this the other way (converting from this format), but I can't find anything on how to output in the ISO 8601 duration format in PHP.

因此,我有一堆人类可读格式的持续时间字符串-我想即时将它们转换为ISO 8601格式,以打印HTML5微数据的持续时间。下面是一些输入的字符串的示例,以及应如何格式化

So I have a heap of duration strings in human readable format - I want to convert them into the ISO 8601 format on the fly to print the durations for HTML5 microdata. Below is a sample of some of the strings coming in, and how they should be formatted

"1 hour 30 minutes" --> PT1H30M
"5 minutes" --> PT5M
"2 hours" --> PT2H

我可以将字符串推入PHP的区间对象中:

I can push the string into an interval object in PHP:

date_interval_create_from_date_string("1 hour 30 minutes");

但似乎没有ISO 8601输出选项

but there doesn't seem to be a ISO 8601 output option

我应该如何处理?

推荐答案

我先将其转换为数字,然后工作

I'd convert it to a number first, then work with that.

首先,使用 strtotime()

First, use strtotime():

$time = strtotime("1 hour 30 minutes", 0);

然后您可以解析其持续时间,并输出为 PnYnMnDTnHnMnS 格式。我会使用以下方法(灵感来自 http://csl.sublevel3.org/php-secs -to-human-text / ):

Then you can parse it for duration, and output in PnYnMnDTnHnMnS format. I'd use the following method (inspired by http://csl.sublevel3.org/php-secs-to-human-text/):

function time_to_iso8601_duration($time) {
    $units = array(
        "Y" => 365*24*3600,
        "D" =>     24*3600,
        "H" =>        3600,
        "M" =>          60,
        "S" =>           1,
    );

    $str = "P";
    $istime = false;

    foreach ($units as $unitName => &$unit) {
        $quot  = intval($time / $unit);
        $time -= $quot * $unit;
        $unit  = $quot;
        if ($unit > 0) {
            if (!$istime && in_array($unitName, array("H", "M", "S"))) { // There may be a better way to do this
                $str .= "T";
                $istime = true;
            }
            $str .= strval($unit) . $unitName;
        }
    }

    return $str;
}

结果: http://codepad.org/1fHNlB6e

这篇关于如何将字符串持续时间转换为ISO 8601持续时间格式? (例如,“ 30分钟”到“ PT30M”)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆