首页 > 解决方案 > Carbon 将天数转换为人类可读的格式

问题描述

我需要将 30 天转换为 1 个月。如果月份和天数是平均值,那么就像 1 年 2 个月 2 天我在下面尝试过,但它会返回错误的结果

 echo CarbonInterval::days(30)->cascade()->forHumans();

谁能帮助我如何实现这一目标?

我尝试了以下解决方案,但只有 2 天的差异

$convert = '30'; // days you want to convert

    $years = ($convert / 365) ; // days / 365 days
    $years = floor($years); // Remove all decimals

    $month = ($convert % 365) / 30.5; // I choose 30.5 for Month (30,31) ;)
    $month = floor($month); // Remove all decimals

    $days = ($convert % 365) % 30.5; // the rest of days

    // Echo all information set
    echo 'DAYS RECEIVE : '.$convert.' days<br>';
    echo $years.' years - '.$month.' month - '.$days.' days';

有没有使用碳的好的解决方案

标签: phplaravellaravel-5php-carbon

解决方案


必须是 CarbonInterval 吗?

怎么样Carbon::now()->subDays(1827)->diffForHumans()

它不能按预期工作的原因(来自https://carbon.nesbot.com/docs/#api-interval):

默认因素是:

  • 1 分钟 = 60 秒
  • 1 小时 = 60 分钟
  • 1 天 = 24 小时
  • 1 周 = 7 天
  • 1 个月 = 4 周
  • 1 年 = 12 个月

CarbonIntervals 不携带上下文,因此它们不能更精确(没有 DST、没有闰年、没有真正的月份长度或年份长度考虑)。


推荐阅读