skip to Main Content

I want to convert Years (with Months in decimal) to Months only via PHP

Like

1.2 Years (1 Year 2 Months) to 14 Months

1.0 Year to 12 Months

I have written the below code that may be having issues so want to correct it.

        $yearwithdecimal = "1.2";
        $yearwithdecimal = (float)$yearwithdecimal;
        if (is_float($yearwithdecimal)) {
            $yearsArray = explode(".",$yearwithdecimal);
            $year_months = $yearsArray[0]*12;
            $more_months = $yearsArray[1];
            $total_months = $year_months + $more_months;
        }else{
            $total_months = $yearwithdecimal*12;
        }
        echo $total_months; die;
        // Output is 14

Thanks in Advance!

3

Answers


  1. You can use round() in php.

    $years = 1.2;
    $months = round($years * 12);
    echo $months.' Months'; //14 Months
    

    *Not quite accurate.

    Login or Signup to reply.
    1. Split the increment value into 2 parts, $incYears and $incMonths
    2. Convert the $incYears into months ($incYears * 12) and add the $incMonths
    3. Add the month to the date
        function addDecimalYears($fromDate, $increment){
            $segments = explode(".", (string)$increment, 2);
            $incYears = isset($segments[0]) ? $segments[0] : 0;
            $incMonths = isset($segments[1]) ? $segments[1] : 0;
    
            $months = 12 * (int)$incYears;
            $months += (int)$incMonths;
    
            $fromDateTimestamp = strtotime($fromDate);
            return date("Y-m-d", strtotime("+" . $months . "month", $fromDateTimestamp));
        }
    
        echo addDecimalYears("2023-11-02", 1.0) . "n";
        echo addDecimalYears("2023-11-02", 1.) . "n";
        echo addDecimalYears("2023-11-02", .12) . "n";
        echo addDecimalYears("2023-11-02", 1.6) . "n";
        echo addDecimalYears("2023-11-02", .18) . "n";
        echo addDecimalYears("2023-11-02", 0.6) . "n";
    

    Output:

    2024-11-02
    2024-11-02
    2024-11-02
    2025-05-02
    2025-05-02
    2024-05-02
    
    Login or Signup to reply.
  2. Suppose your field the first part represents num of years and the second part represents num of months.

    Take the field as a string, then explode it by .

    $yearwithdecimal = "1.2";
    $months = 0;
    if($yearwithdecimal){
        $parts = explode('.', $yearwithdecimal);
        $months = $parts[0]*12 + $parts[1] ?? 0;
    }
    echo $months;
    

    Demo: https://3v4l.org/VhOfV

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search