问题
I am getting the From date and To date using jquery datepicker plugin. The following is the output of POST.
Array (
[fromDate] => 01/03/2012
[toDate] => 15/03/2012
[hdnDownload] => Download
)
I am trying to convert this date format to another date format like this:
echo'fromdate'.$fromDate = date("Y/n/j", strtotime($_POST['fromDate']));
echo'todate'.$toDate = date("Y/n/j", strtotime($_POST['toDate']));
It gives me the following output:
fromdate: 2012-1-3
todate:1969-12-31
The fromDate is fine but the ToDate has changed, can you please help me.
回答1:
You should probably use DateTime::createFromFormat():
php > $date = DateTime::createFromFormat('i/n/Y', '15/03/2012');
php > echo $date->format('Y/n/j');
// 2012/3/11
This is useful because you can specify input format. xx/yy/YY can be represented either as i/n/Y and n/i/Y and therefore date is ambiguous => unpredictable behavior.
回答2:
What you need to make sure you get correct result is either DateTime::createFromFormat() if you're using PHP >= 5.3.0, or strptime() with PHP >= 5.1.0, where you can specify input format.
Although if you still want to allow free format there you might want to make a crutch, that would check with regex for this particular format and use one of these only for american m/d/Y, something like:
function parsedate($date) {
if (preg_match('#\d{1,2}/\d{1,2}/\d{2,4}#', $date)) {
$parsed = strptime($date, '%m/%d/%Y');
return mktime(0, 0, 0, $parsed['tm_mon'], $parsed['tm_mday'], 1900+$parsed['tm_year']);
// 'tm_year' is years since 1900
} else {
return strtotime($date);
}
}
It's still a crutch, but I can't see any cleaner way.
回答3:
strtotime() can give unexpected results if the input is invalid or malformed. It would seem that your $_POST['toDate'] is not valid for strtotimeto function correctly.
The date you do get is the start date of Unix Time in your timezone.
I would suggest using something other than strtotime like the DateTime class or the date() function.
回答4:
The fromDate is also wrong as you wanted 03 to be the month not 1.
In your case strtotime is thinking the input is Month/Day/Year and as 15 is not a month it messes up.
You could either swap your input strings to
[fromDate] => 03/01/2012
[toDate] => 03/15/2012
or use createFromFormat in @Vyktor's answer.
来源:https://stackoverflow.com/questions/9656436/im-weird-with-strtotime-behaviour