0

I have the following timeformat:15/08/2011 12:32:23 day/month/year hour:minute:sec and I want to convert to the following format: Y-m-d H:i:s

I tried with date('Y-m-d H:i:s', strtotime($time)) but it not works. It swaps the month and the day when it's converting from string to datenum.

Matt Gibson
  • 37,886
  • 9
  • 99
  • 128
Mokus
  • 10,174
  • 18
  • 80
  • 122

4 Answers4

2

strtotime understands both American (mm/dd/YYYY) and European (dd-mm-YYYY or dd.mm.YYYY) formats. You are using slashes to separate day, month and year, and that's why your date is interpreted as American. To solve that, replace the slashes with dashes.

Arjan
  • 9,784
  • 1
  • 31
  • 41
  • This one always mildly bemuses me, because I'm European and use slashes. It's not like we all got together over here and decided to teach the same format in all our schools, or anything. Are there no Americans who use dashes? – Matt Gibson Aug 11 '11 at 10:39
  • There probably are, but the PHP manpage http://php.net/manual/en/datetime.formats.date.php reports `mm/dd/YYYY` as American format. And if you want to support both `dd/mm/YYYY` and `mm/dd/YYYY` you'll have to find a way to determine whether `10/01/2011` means `10 Jan 2011` or `01 Oct 2011`. So the Americans got the slashes for their `mm/dd/YYYY` format, and the rest of the world can use tabs, dots or dashes for `dd-mm-YYYY`. If you want to be safe, go for ISO8601 notations. – Arjan Aug 11 '11 at 16:26
0

Replace slashes with hyphen in the date then try it will work.

$a = '07/08/2019'; // 07 is day 08 is month.
echo date('Y-m-d', strtotime($a)); //output: 2019-07-08 where 07 became month.
$a = str_replace("/","-","07/08/2019"); // 07-08-2019
echo date('Y-m-d', strtotime($a)); //2019-08-07
Captain Sparrow
  • 1,114
  • 17
  • 26
0

In which case, you could very simply swap the month and date from your string:

$time_string = "15/08/2011 12:32:23";
$strtotime = explode("/",$time_string);
$strtotime = implode("/",array($strtotime[1], $strtotime[0], $strtotime[2]));
echo date('Y-m-d H:i:s', strtotime($strtotime));

Working Example: http://codepad.viper-7.com/234toO

Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308
0

You are going to have to reparse the time. strtotime is thinking you are trying to input a string in the format of 'm/d/Y H:i:s', but you are supplying 'd/m/Y H:i:s'.

list($date, $times) = explode(' ', $time);
list($day, $month, $year) = explode('/', $date);
$newTime = date('Y-m-d H:i:s', strtotime("$month/$day/$year $times");
Kyle
  • 4,421
  • 22
  • 32