将整数值转换为年、月、周和日


Convert integer value into years, months, weeks and days

我正在处理一个任务,我需要将给定的整数值转换为年,月,周和天的总数

例如,如果给定的值是62个月,那么我应该能够将这个数字转换为x years x months x weeks and x days

我可以在网上找到几个例子,需要2个日期,并给你所需的输出,但我的要求是把数字转换成年,月,周,天。

如果有人能给我指出正确的方向,我将非常感激。

考虑到并非所有月份都相同,因此不可能得到完全准确的结果。在不知道哪个月份和年份的情况下,您可以使用简单的数学方法获得最接近的近似值:

$months = 62;
$days = $months*30; //or 28 or 31 or 29(leap year)
$weeks = $months*4; //or $days/7;
$years = $months/12; //or floor($months/12) . ' years and ' . $months%12 . ' months'
<<p> 看到演示/strong>

"一个月"是指28到31天之间的任何天数。它不能被明确地划分为特定的天数或周数,因为它是一个模糊的时间跨度开始。如果您知道确切的开始日期和"一个月"的明确规格,您就可以得到结果。但是,如果没有更多的说明,仅仅是"62个月"本身是不可能转换的。

你可以使用php内置的DateTime函数,strtotime做得到的结果,你正在寻找一个漂亮的干净的格式。

http://php.net/manual/de/datetime.diff.php

http://de1.php.net/manual/de/function.strtotime.php

$months = 62;
$dateTime = new DateTime();
$newDateTime = $dateTime->diff(
    new DateTime(date("Y-m-d H:i:s", strtotime(sprintf('-%s Months', $months))))
);
print_R($newDateTime);
DateInterval Object
(
    [y] => 5
    [m] => 2
    [d] => 0
    [h] => 0
    [i] => 0
    [s] => 0
    [weekday] => 0
    [weekday_behavior] => 0
    [first_last_day_of] => 0
    [invert] => 1
    [days] => 1887
    [special_type] => 0
    [special_amount] => 0
    [have_weekday_relative] => 0
    [have_special_relative] => 0
)