-3

I am trying to convert this date format mm-dd-yyyy to yyyy-mm-dd I am using strtotime function but it is not coverting properly. date('Y-m-d', strtotime('06-15-2014'))

It is returning date in this format 1970-01-01 01:00:00

  • `DateTime::createFromFormat()` check this out you will get the answer – Abhik Chakraborty May 14 '14 at 10:58
  • Readmore at : http://www.php.net/manual/en/function.strtotime.php Note: 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. To avoid potential ambiguity, it's best to use ISO 8601 (YYYY-MM-DD) dates or DateTime::createFromFormat() when possible. – shyammakwana.me May 14 '14 at 11:03

1 Answers1

0

String functions work too.

$in = "05-14-2004"; // why would you even write dates like this?
$out = substr($in,-4)."-".substr($in,5);
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • Why would you ever use string functions when working with dates when there's DateTime class? – Amal Murali May 14 '14 at 11:06
  • @AmalMurali Simplicity. How many functions do you have to call to get the date parsed and output in the right format? – Niet the Dark Absol May 14 '14 at 11:07
  • `echo DateTime::createFromFormat('m-d-Y', '06-15-2014')->format('Y-m-d');` isn't simple enough? String functions know nothing about dates; it's almost always better to use the appropriate tool for doing something when you have them available. – Amal Murali May 14 '14 at 11:11
  • @AmalMurali Hm. Fair enough, but doesn't that rely on dereferencing, which was only added in PHP 5.4? Anyways... actually, yeah, my code's much more compatible :p But your code is more readable, or at least more obvious what it's doing. – Niet the Dark Absol May 14 '14 at 11:12
  • Nope, it's just method chaining. It should work on any PHP version with DateTime support (method chaining support was added in PHP 5, I think). – Amal Murali May 14 '14 at 11:21