Home > database >  More optimal way to convert dates
More optimal way to convert dates

Time:04-22

I have input string: '10/22' where 10 is number of month and 22 is number of year. I need to convert it to dd-mm-yyyy date. So I wrote script to do it:

<?php

$date = '10/22'; // m-y date
$date = '01/' . $date; // Gets d-m-y date (01/10/22)

$base_year = 2000;
$date_parts = explode('/', $date);
$date_parts[2] = strval(intval($date_parts[2])   $base_year); // Gets 4 digits year (2022)
$date = implode('/', $date_parts); // Joins array elements with a string
$new_date = str_replace('/', '-', $date);

$dmy = DateTime::createFromFormat('d-m-Y', $new_date)->format('d-m-Y'); // Creates date with specified format

echo $dmy; // Will display 01-10-2022, this is what I need

But I am afraid that this way is too bad and I need help to make this script more optimal, if such way exists. Any tips?

CodePudding user response:

You can complete this in just 2 lines with exploding the current date on / and then imploding them later on with an array_merge like below:

<?php

$date = '10/22'; // m-y date

function getFormattedDate($date){
    list($month,$year) = explode("/", $date);
    return implode("-",array_merge(["01"], [$month],["20". $year]));
}

echo getFormattedDate($date);

Online Demo

CodePudding user response:

One liner:

echo DateTime::createFromFormat('d/m/y', '01/'.$date)->format('d-m-Y');

Output : https://3v4l.org/9kb5g

  • Related