Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert Years to Months in PHP

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading