1

I want to convert in php a datetime fr ( 30/11/2016 12:30 ) to a datetime US (2016-11-30 12:30)

Should I use explode then implode or is there a better solution to convert it ?

user492642
  • 169
  • 1
  • 3
  • 12
  • 1
    Possible duplicate of [Convert DateTime to String PHP](http://stackoverflow.com/questions/10569053/convert-datetime-to-string-php) – u_mulder Nov 30 '16 at 11:42
  • And http://stackoverflow.com/questions/2167916/convert-one-date-format-into-another-in-php. And search mooooore. – u_mulder Nov 30 '16 at 11:42
  • Use the [DateTime](http://php.net/manual/en/class.datetime.php) library that comes with PHP, I also did a small write up about using DateTime over at [my blog](http://joshualawson.com.au/date-and-time-in-php/) – Joshua Lawson Nov 30 '16 at 11:51
  • @user492642 , Please mark my answer as accepted if it helped you to close this thread. Thanks, – Abhay Maurya Nov 30 '16 at 13:16

2 Answers2

3

I highly discourage use of "String Functions(str_replace etc.)" to modify datetime strings. Even procedural way should be avoided.

Correct way is to use DateTime class and ofcourse OOP way:

    $time = '30/11/2016 12:30';
    $date = DateTime::createFromFormat('d/m/Y H:i', $time);//assuming you are using 24 hour format for time
    $time = $date->format('Y-m-d H:i');
    echo $time;//2016-11-30 12:30

For more insight, please check: http://php.net/manual/en/datetime.createfromformat.php

I hope it helps

Abhay Maurya
  • 11,819
  • 8
  • 46
  • 64
  • Yeah. That's right. +1. Handling date and time with the dedicated date and time classes and functions is the right way. – Wolverine Nov 30 '16 at 12:39
1
$french_date_string = '30/11/2016 12:30';
$french_date_string = str_replace('/', '-', $french_date_string);

$date = new DateTime($french_date_string);
echo $date->format('Y-m-d H:i');

This code also works. But as far as I'm concerned, Abhay Maurya's answer seems to be more reliable and perfect way of working with datetime with the dedicated datetime classes and functions.

Wolverine
  • 1,712
  • 1
  • 15
  • 18