Parse and create ISO 8601 Date and time intervals, like PT15M in PHP

前端 未结 5 462
無奈伤痛
無奈伤痛 2020-12-29 21:23

A library and webservice I am using communicates time-intervals in ISO 8601 format: PnYnMnDTnHnMnS. I want to convert such formats to seconds. And vice versa. Seconds are a

5条回答
  •  Happy的楠姐
    2020-12-29 21:45

    function parsePTTime($pt_time)
    {
        $string = str_replace('PT', '', $pt_time);
        $string = str_replace('H', 'Hour', $string);
        $string = str_replace('M', 'Minute', $string);
        $string = str_replace('S', 'Second', $string);
    
        $startDateTime = '19700101UTC';
        $seconds = strtotime($startDateTime . '+' . $string) - strtotime($startDateTime);
    
        return $seconds;
    }
    

    Tests:

    PT1H         - OK
    PT23M        - OK
    PT45S        - OK
    PT1H23M      - OK
    PT1H45S      - OK
    PT23M45S     - OK
    PT1H23M45S   - OK
    

提交回复
热议问题