Search code examples
phplaravellaravel-5php-carbon

Carbon convert no of days to human readable format


I need to convert 30 days to 1 month .If months and days are means then like 1 years 2 month 2 days I have tried below but it will return wrong result

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

Can any one help me how i can achieve this ?

I have tried below solution but got only 2 days difference

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

Is there any good solution using carbon


Solution

  • Does it have to be CarbonInterval?

    What about Carbon::now()->subDays(1827)->diffForHumans()?

    The reason it doesn't work as you're expecting (from 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).