Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP convert date format dd/mm/yyyy => yyyy-mm-dd [duplicate]

I am trying to convert a date from dd/mm/yyyy => yyyy-mm-dd. I have using the mktime() function and other functions but I cannot seem to make it work. I have managed to explode the original date using '/' as the delimiter but I have no success changing the format and swapping the '/' with a '-'.

Any help will be greatly appreciated.

like image 965
Daniel Mabinko Avatar asked Apr 24 '12 22:04

Daniel Mabinko


People also ask

What is Strtotime PHP?

The strtotime() function parses an English textual datetime into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 GMT). Note: If the year is specified in a two-digit format, values between 0-69 are mapped to 2000-2069 and values between 70-100 are mapped to 1970-2000.

How do I format in PHP?

a - Lowercase am or pm. A - Uppercase AM or PM. B - Swatch Internet time (000 to 999) g - 12-hour format of an hour (1 to 12)

How can get date in dd-mm-yyyy format in MySQL?

The MySQL DATE_FORMAT() function formats a date value with a given specified format. You may also use MySQL DATE_FORMAT() on datetime values and use some of the formats specified for the TIME_FORMAT() function to format the time value as well. Let us take a look at the syntax of DATE_FORMAT() and some examples.


2 Answers

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. Check more here.

Use the default date function.

$var = "20/04/2012"; echo date("Y-m-d", strtotime($var) ); 

EDIT I just tested it, and somehow, PHP doesn't work well with dd/mm/yyyy format. Here's another solution.

$var = '20/04/2012'; $date = str_replace('/', '-', $var); echo date('Y-m-d', strtotime($date)); 
like image 143
hjpotter92 Avatar answered Sep 19 '22 13:09

hjpotter92


Try Using DateTime::createFromFormat

$date = DateTime::createFromFormat('d/m/Y', "24/04/2012"); echo $date->format('Y-m-d'); 

Output

2012-04-24 

EDIT:

If the date is 5/4/2010 (both D/M/YYYY or DD/MM/YYYY), this below method is used to convert 5/4/2010 to 2010-4-5 (both YYYY-MM-DD or YYYY-M-D) format.

$old_date = explode('/', '5/4/2010');  $new_data = $old_date[2].'-'.$old_date[1].'-'.$old_date[0]; 

OUTPUT:

2010-4-5 
like image 31
Baba Avatar answered Sep 17 '22 13:09

Baba