简体   繁体   English

PHP:将年份转换为月份和月份日期

[英]PHP: Convert Day of Year to Day of Month and Month

If you have the day of the year. 如果你有一年中的哪一天。 How can you convert that to day of month and month? 你怎么能把它转换成月和月的某一天? For example: The day "144" should be converted to 26th of May. 例如:“144”日应转换为5月26日。 I guess I also have to add the actual year to account for leap years. 我想我还要加上实际的年份来说明闰年。 But I haven't found anything at all. 但我还没有发现任何东西。

For example the function mktime() exepects the month, year and day of month. 例如,函数mktime()会记录月份,年份和日期。

Anybody some suggestions? 有人提出一些建议吗?

The most reliable and convenient way is to use the DateTime object. 最可靠和方便的方法是使用DateTime对象。 You can use DateTime::createFromFormat() static method to create it based on day in the current year: 您可以使用DateTime :: createFromFormat()静态方法根据当前年份的日期创建它:

$date = DateTime::createFromFormat('z', '144');

And because you know have DateTime object in the $date variable, you can perform literally any task you want to. 而且因为你知道在$date变量中有DateTime对象,所以你可以执行任何你想要的任务。 To output the contained date, simply call: 要输出包含的日期,只需调用:

echo $date->format('j. n. Y');

It will print out 24. 5. 2012, because it's leap year and because it indexes days starting from zero (just like array indices). 它将打印出24. 5. 2012,因为它是闰年,因为它从零开始索引天数(就像数组索引一样)。

strtotime("January 1st +".($days-1)." days");

这将返回与一年中指定日期相对应的时间戳。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM