dongpu1908 2018-01-30 14:55
浏览 45
已采纳

将PHP DateInterval转换为期间规范[重复]

This question already has an answer here:

Using PHP, I want to be able to go from a strtotime relative time to a datetime interval that can be used for an iCalendar duration.

An example would be something like:

$date = \DateInterval::createFromString('5 minutes');
$period = $date->doSomeMagic();
echo $period; // should echo "PT5M"

Are there any built-in PHP functions to do this? Or if there aren't, is there a library that can do it?

</div>
  • 写回答

1条回答 默认 最新

  • dongqiya9552 2018-01-30 15:15
    关注

    Perhaps something like this

    $date = \DateInterval::createFromDateString('2 days 5 minutes');
    
    function doSomeMagic(\DateInterval $date) {
        $interval = 'P' .
            ($date->y == 0 ? null : $date->y . 'Y') .
            ($date->m == 0 ? null : $date->m . 'M') .
            ($date->d == 0 ? null : $date->d . 'D');
        $timeInterval =
            ($date->h == 0 ? null : $date->h . 'H') .
            ($date->i == 0 ? null : $date->i . 'M') .
            ($date->s == 0 ? null : $date->y . 'S');
        return $interval . ((!empty($timeInterval)) ? 'T' . $timeInterval : null);
    }
    
    
    $period = doSomeMagic($date);
    echo $period;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥66 换电脑后应用程序报错
  • ¥50 array数据同步问题
  • ¥15 pic16F877a单片机的外部触发中断程序仿真失效
  • ¥15 Matlab插值拟合差分微分规划图论
  • ¥15 keil5 target not created
  • ¥15 C/C++数据与算法请教
  • ¥15 怎么找志同道合的伙伴
  • ¥20 如何让程序ab.eXe自已删除干净硬盘里的本文件自己的ab.eXe文件
  • ¥50 爬虫预算充足,跪巨佬
  • ¥15 滑块验证码拖动问题悬赏