'How to change date format using PHP? [duplicate]
I have input string: '10/22' where 10 is a number of month and 22 is a number of year. I need to convert it to dd-mm-yyyy date. So I wrote a 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?
Solution 1:[1]
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);
Solution 2:[2]
One liner:
echo DateTime::createFromFormat('d/m/y', '01/'.$date)->format('d-m-Y');
Output : https://3v4l.org/9kb5g
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | nice_dev |
| Solution 2 | Anant Kumar Singh |
