0

I got this type of date from DB '10/09/19' It's today date(10th sept 2019).

$date = '10/09/19';
       //DD/MM/YY
$newdate=date('Y-m-d',strtotime(str_replace('/', '-', $date)));
echo $newdate; //output 2010-09-19
exit;

It's giving me 2010-09-19. it means 19th Sept 2010.

I expect 10-09-2019(10th Sept 2019). I already tried many solutions from SO but no luck. Can anyone tell me what am I doing wrong??

Dilip Hirapara
  • 14,810
  • 3
  • 27
  • 49
  • 3
    check out `DateTime` ~ specifically `DateTime::createFromFormat ` – Professor Abronsius Sep 10 '19 at 12:55
  • 2
    `Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed. If, however, the year is given in a two digit format and the separator is a dash (-), the date string is parsed as y-m-d.` From the docs. Specifically, **If, however, the year is given in a two digit format and the separator is a dash (-), the date string is parsed as y-m-d.** – aynber Sep 10 '19 at 12:57
  • https://3v4l.org/hSBtj – Nick Sep 10 '19 at 12:59
  • @Nick Your last fiddle comment worked for me. Thanks for it. Add it in answer I'll select it. – Dilip Hirapara Sep 10 '19 at 13:02
  • 2
    @DilipHirapara having closed the question as a duplicate no-one can post answers any more. I'm happy enough that you have a solution. – Nick Sep 10 '19 at 13:03

1 Answers1

1

The DateTime class can be used in situations like this - it has the useful method createFromFormat

    $date='10/09/19';   //dd/mm/yy
    $new=DateTime::createFromFormat('d/m/y', $date )->format('Y/m/d');
    echo $new;  //2019/09/10
Professor Abronsius
  • 33,063
  • 5
  • 32
  • 46