strtotime() throws false on a formatted date

2019-07-24 16:59发布

问题:

I'm having a problem with converting a formatted date string into a integer timestamp. I'm using a datepicker to input a field such as DD/MM/YY and I'm using strtotime to change it.

Example usage

$date_from = (!empty($_POST['datefrom'])) ? (string) $db->sql_escape($_POST['datefrom']) : false;
$date_to   = (!empty($_POST['dateto'])) ? (string) $db->sql_escape($_POST['dateto']) : false;

$time_from = (!empty($_POST['timefrom'])) ? (string) $db->sql_escape($_POST['timefrom']) : '';
$time_to   = (!empty($_POST['timeto'])) ? (string) $db->sql_escape($_POST['timeto']) : '';

Dumps

var_dump($_POST); 
var_dump($date_from . ' ' . $time_from);
var_dump($date_to . ' ' . $time_to);

Outputs

array(4) {
  ["datefrom"]=>
  string(10) "23/03/2011"
  ["dateto"]=>
  string(10) "18/04/2011"
  ["timefrom"]=>
  string(5) "01:26"
  ["timeto"]=>
  string(5) "04:44"
}
string(16) "23/03/2011 01:26"
string(16) "18/04/2011 04:44"

Now you can see each variable are not empty, now nothing is returning (except false) when using strtotime with this:

$range_from = strtotime($date_from . ' ' . $time_from);
$range_to   = strtotime($date_to . ' ' . $time_to);

var_dump($range_from);
var_dump($range_to);

Outputs

bool(false)
bool(false)

Now that's where I'm stuck thinking why it's not converting a DD/MM/YY HH:MM into a timestamp, I hardly can find what's wrong with it...

回答1:

See http://php.net/strtotime

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.

23/03/2011 in m/d/y is invalid, as such the function returns false.