【问题标题】:PHP - convert seconds to months using only datetimePHP - 仅使用日期时间将秒转换为月
【发布时间】:2020-09-07 16:45:00
【问题描述】:

从Convert seconds into days, hours, minutes and seconds我们可以得到User Galvic的好功能:

function secondsToTime($seconds){
    $dtF = new \DateTime('@0');
    $dtT = new \DateTime("@$seconds");
    return $dtF -> diff($dtT) -> format('%a days, %h hours, %i minutes and %s seconds');
    }

echo secondsToTime(3600 * 24 * 31);

这很好用!但我想添加月份,然后我把 %m 个月 返回 0,%M 个月 返回两位数。

如何转换[1个月2天]的3600 * 24 * 32和[1年1个月]的3600 * 24 * 30 * 13?

因为Function of Galvic 中存在许多选项,但只有一个使用 2 行:GALVIC 函数,然后我想在这两行中添加选项“月、年”。

谢谢

【问题讨论】:

标签: php


【解决方案1】:

几天内不要使用 %a,改用 %d。

return $dtF->diff($dtT)->format('%y years, %m months, %d days');

【讨论】:

  • 感谢@Vladan,secondsToTime(3600 * 24 * 31); 返回 1 个月; PHP 中的月份是 31 天?
  • @Stackoverflow 不,诀窍是我们正在测量 1970 年 1 月 1 日 (@0) 和 1970 年 2 月 1 日 (3600 * 24 * 31) 之间的差异,因此差异确实是 1 个月。但是尝试将开始日期设置为 1970 年 2 月 1 日并将其与 3 月 2 日进行比较,例如,您会得到 1 month and 1 day
猜你喜欢
  • 2011-05-22
  • 1970-01-01
  • 1970-01-01
  • 2017-10-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-06
相关资源
最近更新 更多