-2

I have a biometric device which gives date format in d/m/Y h:i:s but I want to convert the same information to Y-m-d.

$var = d/m/Y h:i:s ;
echo convert($var); // Output want: Y-m-d

But if date is 10-11-2015 then how php will know that the format is d-m-y or m-d-y ?

I know how to convert yyyy-mm-dd to dd-mm-yyyy, but want dd-mm-yyyy to yyyy-mm-dd

How Can I do that ?

Haren Sarma
  • 2,267
  • 6
  • 43
  • 72
  • 3
    Possible duplicate of [Convert date format yyyy-mm-dd => dd-mm-yyyy](http://stackoverflow.com/questions/2487921/convert-date-format-yyyy-mm-dd-dd-mm-yyyy) – Mureinik Nov 28 '15 at 09:03
  • I know how to convert yyyy-mm-dd to dd-mm-yyyy, but want dd-mm-yyyy to yyyy-mm-dd – Haren Sarma Nov 28 '15 at 09:04
  • php `date()` 1st paramiter is `format` http://php.net/manual/en/function.date.php – manta Nov 28 '15 at 09:10

2 Answers2

3

use the DateTime class

$date = DateTime::createFromFormat('d/m/y', '28/11/15');
echo $date->format('Y-m-d');

outputs

2015-11-28

Or you could do it on one line if you like that sort of thing:

echo \DateTime::createFromFormat('d/m/y', '28/11/15')->format('Y-m-d');

also read the note from here manual

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. If, however, the year is given in a two digit format and the separator is a dash (-, the date string is parsed as y-m-d. To avoid potential ambiguity, it's best to use ISO 8601 (YYYY-MM-DD) dates or DateTime::createFromFormat() when possible.

vascowhite
  • 18,120
  • 9
  • 61
  • 77
roullie
  • 2,830
  • 16
  • 26
  • 1
    based on your example, just a Note: you would actually echo $date->format('Y-m-d'); and not from $datetime. – Ivan Veštić Nov 28 '15 at 12:08
  • 1
    I edited your code as [DateTime::createFromFormat()](http://php.net/manual/en/datetime.createfromformat.php) is a static function that [returns an instance of DateTime](http://php.net/manual/en/datetime.createfromformat.php#refsect1-datetime.createfromformat-returnvalues). – vascowhite Nov 29 '15 at 13:39
0

Try this:

$var = date('d/m/Y h:i:s');

$datetime = explode(' ', $var);
$date_string = implode('-', array_reverse(explode('/', $datetime[0])));
$time_string = $datetime[1];

$formated = date('Y-m-d', strtotime("{$date_string} {$time_string}"));

echo "<pre>";
print_r($formated); // test output
echo "</pre>";