将DateInterval格式设置为ISO8601 [英] Format DateInterval as ISO8601

查看:112
本文介绍了将DateInterval格式设置为ISO8601的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在处理一个php项目,需要将DateInterval格式化为ISO8601(类似这样):

  P5D 

此格式可用于创建DateTime和DateInterval对象,但我找不到解决方法将DateInterval格式化为这种格式。有没有?如果不是,那么什么可能是轻量级的解决方案呢?

解决方案

好吧,如果您在查看格式规范时构造一个:


Y年



M个月



D天



W周。



H小时



M分钟 p>

S秒


然后看看您需要使用什么( href = http://php.net/manual/en/dateinterval.format.php rel = nofollow> http://php.net/manual/en/dateinterval.format.php ),似乎您应该做的是:

  $ dateInterval = new DateInterval(/ *不管* /); 
$ format = $ dateInterval-> format( P%yY%mM%dD%hH%iM%sS);
// P0Y0M5D0H0M0S
//现在,我们需要删除所有为零的东西,但请确保不要删除
//类似10D或20D
$ format = str_replace ([[ M0S, H0M, D0H, M0D, Y0M, P0Y],[ M, H, D, M, Y0M, P ],$ format);
echo $ format;
// P0M5D

现在,我做不同的一件事就是我总是包括月份,即使它是0。原因是分钟两者都由 M 表示-如果我们始终包括月份,那么如果有分钟,我们就知道是分钟。否则,我们必须做一堆逻辑来看看是否需要将 P 更改为 PT ,以便知道在这种情况下,a M 代表分钟



例如:

  // 3个月
new DateInterval( P3M);
// 3分钟
new DateInterval( PT3M));

但我们却这样做:

  // 3个月
新的DateInterval( P3M);
// 3分钟
new DateInterval( P0M3M));


I am currently working on a php project and need to format a DateInterval as ISO8601 (something like this):

P5D

This format can be used to create DateTime and DateInterval objects, but I can't figure out a way to format a DateInterval into this format. Is there any? If not, what might be a lightweight solution to that?

解决方案

Well, if you look at the spec for the format when you construct one:

Y years

M months

D days

W weeks. These get converted into days, so can not be combined with D.

H hours

M minutes

S seconds

Then look at what you have to work with (http://php.net/manual/en/dateinterval.format.php), it seems like what you would do is:

$dateInterval = new DateInterval( /* whatever */ );
$format = $dateInterval->format("P%yY%mM%dD%hH%iM%sS");
//P0Y0M5D0H0M0S
//now, we need to remove anything that is a zero, but make sure to not remove
//something like 10D or 20D
$format = str_replace(["M0S", "H0M", "D0H", "M0D", "Y0M", "P0Y"], ["M", "H", "D", "M", "Y0M", "P"], $format);
echo $format;
//P0M5D

Now, the one thing I did differently is I always include the months, even if it is 0. The reason for this is that minutes and months are both represented by M - if we always include the month, then if there is a minute we know it is minutes. Otherwise we have to do a bunch of logic to see if we need to change the P to PT so it knows that the a M in this instance stands for Minute.

For example:

// For 3 Months
new DateInterval("P3M");
// For 3 Minutes
new DateInterval("PT3M"));

But instead we do:

// For 3 Months
new DateInterval("P3M");
// For 3 Minutes
new DateInterval("P0M3M"));

这篇关于将DateInterval格式设置为ISO8601的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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