Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

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

like image 351
Mak Avatar asked Jan 01 '14 12:01

Mak


People also ask

How can I get current date in YYYY-mm-DD format in PHP?

date_default_timezone_set('UTC'); echo "<strong>Display current date dd/mm/yyyy format </strong>". "<br />"; echo date("d/m/Y"). "<br />"; echo "<strong>Display current date mm/dd/yyyy format</strong> "."<br />"; echo date("m/d/Y")."<br />"; echo "<strong>Display current date mm-dd-yyyy format </strong>".


3 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.

like image 193
Amal Murali Avatar answered Oct 10 '22 17:10

Amal Murali


Try this

$birthdate= strtotime($_POST['brithday']);
$brithdateFormated = date("d/m/Y",$birthdate);
like image 44
Rizwan Sultan Avatar answered Oct 10 '22 15:10

Rizwan Sultan


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.

like image 30
Parth Patel Avatar answered Oct 10 '22 16:10

Parth Patel