-2

I'm trying to convert convert dd/mm/yy to yyyy-mm-dd. After i researched several methods and I found this.

$var = '20/01/2021'; 
$date = str_replace('/', '-', $var); 
$show_date = date('Y-m-d', strtotime($date));

It works fine with result 2021-01-20. However, my input was two digit yy only which is 20/01/21 and the result became 2020-01-21.

jaydon.T
  • 17
  • 4

1 Answers1

1

With an ambigous date like you have it is better to use the DateTime class as you can set the input format. See the following example from the documentation:

$var = '20/01/21'; 

$date = DateTime::createFromFormat('d/m/y', $var); // "d/m/y" corresponds to the input format
echo $date->format('Y-m-d'); //outputs 2021-01-20
cOle2
  • 4,725
  • 1
  • 24
  • 26