0

I have the following query in my page ?filterFrom=11%2F01%2F2014&filterTo=11%2F25%2F2014

Now I have the following code

// Get Start
if(isset($_GET['filterFrom']) && !empty($_GET['filterFrom'])) {
    $startDate = new DateTime(str_replace('/', '-', $_GET['filterFrom']));
    $sqlArray[":searchFrom"] = $startDate->format('Y-m-d').' 00:00:00';
}
// Get End
if(isset($_GET['filterTo']) && !empty($_GET['filterTo'])) { 
    $endDate = new DateTime(str_replace('/', '-', $_GET['filterTo']));
    $sqlArray[":searchTo"] = $endDate->format('Y-m-d').' 23:59:59';
}

The "Get Start" part of the script works fine, but when it gets to "Get End", I get the following error:

Fatal error: Uncaught exception 'Exception' with message 'DateTime::__construct(): Failed to parse time string (11-25-2014) at position 0 (1): Unexpected character'

I have this exact same script on 6 other pages and don't have any issues! Does anyone know what could be going wrong??

Tim Wißmann
  • 647
  • 6
  • 18
dpDesignz
  • 1,909
  • 10
  • 34
  • 70
  • can you show the actual $_GET['filterTo'] ? – Milad Nov 23 '14 at 22:12
  • Sorry I don't understand what you mean? It's in the query up the top `filterTo=11%2F25%2F2014` – dpDesignz Nov 23 '14 at 22:14
  • 1
    You're using `-` as a date separator instead of `/` (which itself results in ambiguous dates: `MM/dd/yyyy` vs `dd/MM/yyyy`). Use `date_parse_from_format` instead to specify the format of the input string so it's parsed unambiguously. – Dai Nov 23 '14 at 22:14
  • @Dai thanks, my script is localized to New Zealand where I am. But like I said, it's only this one line it fails on. It works the other 15 odd times it's in my site. :/ I'll give that a go – dpDesignz Nov 23 '14 at 22:16
  • please , echo str_replace('/', '-', $_GET['filterTo'] , to see what is the actual input to the DateTime , – Milad Nov 23 '14 at 22:20
  • @xe4me it literally gives me `11-25-2014`. Doesn't even have any whitespace – dpDesignz Nov 23 '14 at 22:22
  • Check out this answer : http://stackoverflow.com/questions/18836313/adding-two-datetime-objects-in-php – Milad Nov 23 '14 at 22:25
  • Sorry I'm not sure how that applies to my issue? I'm not doing anything with time intervals. I literally just want to construct a date from a query for an SQL search. I've ended up going with `$endDate = DateTime::createFromFormat('d/m/Y', $_GET['filterTo']);` – dpDesignz Nov 23 '14 at 22:34
  • The format you are supplying to the \DateTime constructor is not a [recognised date format](http://php.net/manual/en/datetime.formats.date.php) in PHP. – vascowhite Nov 25 '14 at 14:53
  • @vascowhite but as above, it works all over my site, apart from this one line. It's so weird! – dpDesignz Nov 25 '14 at 19:26

1 Answers1

0

It turns out php was having an issue parsing my date, so I used the following code

$endDate = DateTime::createFromFormat('d/m/Y', $_GET['filterTo']);
dpDesignz
  • 1,909
  • 10
  • 34
  • 70