Carbon 将天数转换为人类可读的格式

Carbon convert no of days to human readable format

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

 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';

有没有用carbon的好办法

一定要CarbonInterval吗?

Carbon::now()->subDays(1827)->diffForHumans()呢?

它没有像您期望的那样工作的原因(来自 https://carbon.nesbot.com/docs/#api-interval):

Default factors are:

  • 1 minute = 60 seconds
  • 1 hour = 60 minutes
  • 1 day = 24 hour
  • 1 week = 7 days
  • 1 month = 4 weeks
  • 1 year = 12 months

CarbonIntervals do not carry context so they cannot be more precise (no DST, no leap year, no real month length or year length consideration).