strtotime() converts a non existing date to another date

风流意气都作罢 提交于 2019-12-11 02:48:56

问题


I am building a timestamp from the date, month and year values entered by users.

Suppose that the user inputs some wrong values and the date is "31-02-2012" which does not exist, then I have to get a false return. But here its converting it to another date nearby. Precisely to: "02-03-2012"..

I dont want this to happen..

$str = "31-02-2012";
echo date("d-m-Y",strtotime($str)); // Outputs 02-03-2012

Can anyone help? I dont want a timestamp to be returned if the date is not original.


回答1:


That's because strtotime() has troubles with - since they are used to denote phrase like -1 week, etc...

Try

$str = '31-02-2012';
echo date('d-m-Y', strtotime(str_replace('-', '/', $str)));

However 31-02-2012 is not a valid English format, it should be 02-31-2012.


If you have PHP >= 5.3, you can use createFromFormat:

$str = '31-02-2012';
$d = DateTime::createFromFormat('d-m-Y', $str);
echo $d->format('d-m-Y');



回答2:


You might look into checkdate.




回答3:


You'll have to check if the date is possible before using strtotime. Strtotime will convert it to unix date meaning it will use seconds since... This means it will always be a date.




回答4:


You can workaround this behavior

<?php
$str = "31-02-2012";
$unix = strtotime($str); 
echo date('d-m-Y', $unix);
if (date('d-m-Y', $unix) != $str){
   echo "wrong";
}
else{
   echo date("d-m-Y", $unx);
}

or just use checkdate()




回答5:


Use the checkdate function.

$str = "31-02-2012";
$years = explode("-", $str);
$valid_date = checkdate($years[1], $years[0], $years[2]);

Checkdate Function - PHP Manual & Explode Function - PHP Manual




回答6:


Combine date_parse and checkdate to check if it's a valid time.

<?php
date_default_timezone_set('America/Chicago');

function is_valid_date($str) {
    $date = date_parse($str);
    return checkdate($date['month'], $date['day'], $date['year']);
}

print is_valid_date('31-02-2012') ? 'Yes' : 'No';
print "\n";
print is_valid_date('28-02-2012') ? 'Yes' : 'No';
print "\n";

Even though that date format is acceptable according to PHP date formats, it may still cause issues for date parsers because it's easy to confuse the month and day. For example, 02-03-2012, it's hard to tell if 02 is the month or the day. It's better to use the other more specific date parser examples here to first parse the date then check it with checkdate.



来源:https://stackoverflow.com/questions/7583579/strtotime-converts-a-non-existing-date-to-another-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!