0

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?

Siddharth Rathod
  • 634
  • 1
  • 7
  • 21
WideWood
  • 549
  • 5
  • 13

2 Answers2

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);

Online Demo

nice_dev
  • 17,053
  • 2
  • 21
  • 35
  • What is advantage of using list? – WideWood Apr 22 '22 at 04:37
  • @WideWood It simplye creates those 2 variables and injects the values respectively received from explode function. https://www.php.net/manual/en/function.list.php I used it here for clean and readable code. – nice_dev Apr 22 '22 at 04:39
  • You can use list when a function returns an array, or you could use it on an array directly. list( $a, $b ) = [ 1, 2, 3, 4, 5 ]; $a will be 1, $b will be 2. Its the same as $arr = [ 1, 2, 3, 4, 5 ]; $a = $arr[0]; $b = $arr[1]; – Joel M Apr 22 '22 at 06:56
0

One liner:

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

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

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
Jacob Mulquin
  • 3,458
  • 1
  • 19
  • 22