phptimetext-parsingunits-of-measurementdelimited

Convert years.months formatted string to months in PHP


Unfortunately, I have data from a client in an unusual format. I expected years and months in separate columns, but instead, it comes as a dot-delimited string: [years].[months].

I have imported this data into MySql Database and now requires to convert years.months to months on which I am going to set some action further.

So I want to convert years (with months after the decimal) to months only in PHP.

Test cases:

I have written the below code that may be having issues so I 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

Solution

  • 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