Home » Php » How to change date format d/m/Y to Y-m-d PHP

How to change date format d/m/Y to Y-m-d PHP

Posted by: admin July 12, 2020 Leave a comment

Questions:

I want to keep date format d/m/Y (24/12/2013) in client side (users enter date in that format from JQuery date picker). But in server side I convert it to Y-m-d(2013-12-24) format.

To do that I wrote code in this way

$brithdate = explode('/', $_POST['brithday']);
$brithdateFormated = $brithdate[2] . "-" . $brithdate[1] . "-" . $brithdate[0];

Is this correct? or is there any easy way to do that

How to&Answers:

Use DateTime objects when you’re working with dates and times. You can use DateTime::createFromFormat() to parse the date string and then the DateTime::format() to format it the way you want:

$str = '24/12/2013';
$date = DateTime::createFromFormat('d/m/Y', $str);
echo $date->format('Y-m-d'); // => 2013-12-24

For a list of available formatting options, see the documentation.

Answer:

Try this

$birthdate= strtotime($_POST['brithday']);
$brithdateFormated = date("d/m/Y",$birthdate);

Answer:

This is working for me.

$start_date='04/05/2018';
$convertedDate= DateTime::createFromFormat('d/m/Y', $start_date)->format('Y-m-d');

Note: The First parameter should be same as your $start_date with ‘/’ also. If you put ‘-‘ there, then it will not perform the correct conversion.