2

I want to find whether a date is in "j/n/Y" format or not, if its is then i want to convert ot to "d/m/Y". If it is already in "d/m/Y" format i dont want any alteration in it.

I tried this-

         $date = '1/7/2019'; 

here i am assuming 1 as date, 7 as month, and 2019 as year(obviously). Now,

        $date_format_changed = date("d/m/Y", strtotime($date));

this above code gives me output as "07/01/2019". But i want output as "01/07/2019".

and if date is already in d/m/Y format eg- 17/12/2019, when this string will be passed in above date conversion code, it gives me output "01/01/1970". Dont know why.

Please help!

  • 1
    That's going to be very difficult to check. 1/7/2019 would be valid as both July 1st and January 7th. It's easier with days greater than 12, but less than that would be iffy. – aynber Jul 03 '19 at 13:17
  • The note for [strtotime](https://www.php.net/manual/en/function.strtotime.php) says `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.` – aynber Jul 03 '19 at 13:17
  • If you know that the string always is either `j/n/Y` or `d/m/Y`, then you can check the length. If the length of the date string is 8 or 9, then it's the `j/n/Y`. If the length is 10, then it's `d/m/Y`. – M. Eriksson Jul 03 '19 at 13:23

2 Answers2

2

An approach could be to explode the date into its day month and year components, and then analyse it

$date = '1/7/2019'; 

$array = explode("/", $date);

$day = $array[0];
$month = $array[1];
$year = $array[2];

if(strlen($day) == 1) $day = "0".$day;
if(strlen($month) == 1) $month = "0".$month;

echo $day."/".$month."/".$year;
Manav
  • 1,357
  • 10
  • 17
  • You could simply do a `strlen($date)`. If the length is 8 or 9, it's `j/n/Y` and if it's 10, it's `d/m/Y` – M. Eriksson Jul 03 '19 at 13:25
  • 1
    @MagnusEriksson- Yes we can do that, but we still need to explode the $date variable to concatenate 0 with day and month, so that we can achieve date in d-m-Y format. – KUSHAL AGRAWAL Jul 03 '19 at 14:05
1

You can "help" the interpreter to guess the correct format.

date_create_from_format is one way to do this.

$date = '1/7/2019';
$parsed = date_create_from_format("j/n/Y", $date);

if ($parsed == false) {
    // Not in j/n/Y format
} else {
    $dmY = $parsed->format("d/m/Y");
}

Note that this will also parse dates which theoretically match j/n/Y but are intended in a different way. (e.g. when you use d/m/Y it might also detect m/d/Y)

Kryptur
  • 745
  • 6
  • 17