2

I'm trying to format a date in the form mm-dd-yyyy to the form yyyy-mm-dd, however, when I try formatting it, it comes out as 1969-12-31.

Here's my code:

$custom_date = "10-13-2013";

$formatted_date = date("Y-m-d", strtotime($custom_date));

What's wrong?

Burrows
  • 475
  • 2
  • 8
  • 18
  • 1
    You haven't posted the date you're starting with. Note that `strtotime()` is not infallible, and depending on exactly what you have in your date it can make some wild errors. –  Oct 13 '13 at 21:11
  • What is `$_GET['date']` – Blazer Oct 13 '13 at 21:12
  • I'd suggest using `DateTime` with the `createFromFormat` method, which can parse the date based on the format you give. – Sven Oct 13 '13 at 21:13
  • There, edited the post. – Burrows Oct 13 '13 at 21:13
  • as Mike said, and maybe using `htmlspecialchars` etc etc might mess up what's going into `strtotime`. At the end of the day, if someone puts a tag or something into your GET variable, date will still return a date of some sort so I'd suggest removing them. – scrowler Oct 13 '13 at 21:14
  • here you go: [answer](http://stackoverflow.com/a/2891949/1974106). You have mm-dd-yyyy not dd-mm-yyyy – Triple_6 Oct 13 '13 at 21:24
  • The european **standard** is day/month/year, that works `echo date("Y-m-d",strtotime("13-10-2013")), PHP_EOL;` ... for arbitrary format, see http://stackoverflow.com/a/2767419/287948 – Peter Krauss Aug 22 '15 at 19:31

2 Answers2

5
$custom_date = "10-13-2013";

$formatted_date = DateTime::createFromFormat("m-d-Y", $custom_date)->format("Y-m-d");
Sven
  • 69,403
  • 10
  • 107
  • 109
4

mm-dd-yyyy is not a format that is recognised by strtotime. That's because it wouldn't reliably be able to handle dates like 03-04-2013, it is the fourth of March or the third of April?

You need to parse it manually, or use the DateTime class.

list($m,$d,$y) = explode("-",$_GET['date']);
$timestamp = mktime(0,0,0,$m,$d,$y);
$formatted_date = date("Y-m-d",$timestamp);
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592