Warm tip: This article is reproduced from stackoverflow.com, please click
date php strtotime

How to check whether a date is in j-n-Y format or not? if yes then how to convert it to d-m-Y format

发布于 2020-03-27 10:15:31

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!

Questioner
KUSHAL AGRAWAL
Viewed
164
Manav 2019-07-03 21:21

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;