Search code examples
phpdatedate-formatstrtotime

Simplest and easiest way to convert dd/mm/yy to date in php


I am yet to find a simple way to do this and very few places address date formats with 2 years. I have read strtotime() and it really only handles 4 digit years or American format - which doesn't help me.

In the end, I generally end up breaking the string into an array, adding 20 in front of year and converting with that BUT that just seems really cumbersome.

I toiled with this example: http://php.net/manual/en/function.strtotime.php#100144 and couldn't get it to work... It seemed so simple... then I read the notes;

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.

Is there a more economical way of processing these dates or will I forever be forced to perform 3-4 lines of conversion every time?

RO Date: 19/04/18
RO Date: 18/06/18
RO Date: 19/06/18
RO Date: 19/06/18
RO Date: 19/06/18


Solution

  • Simplest and easiest way to convert dd/mm/yy to date in php?

    Use DateTime::createFromFormat():

    <?php
    $date = '24/03/83';
    //
    echo date_create_from_format('d/m/y', $date)->format('Y-m-d');
    

    Or

    <?php
    $date = '24/03/83';
    //
    echo DateTime::createFromFormat('d/m/y', $date)->format('Y-m-d');
    

    Result:

    1983-03-24
    

    https://3v4l.org/KIVbM

    Use Y if year is 1983, see manual link above for all formats.