开发者

strtotime() doesn't warn of invalid dates

I am using strtotime to parse a date that is like 10:24 AM 开发者_JS百科22-Sep I was then parseing this thru checkdate

 $pickup_time = strtotime($pickupTime);
 if (!checkdate(date(n,$pickup_time) ,date(j,$pickup_time), date(Y,$pickup_time)));
 {  
 echo json_encode(array("msg"=>"Nice one, that date doesn't exist. Try again.","status"=>"false")); 
 break;     
 }

But strtotime converts bad dates to the next logical date it would seem. So 31st Sep becomes 1 October. Completely voiding the checkdate function. Should you be able to use strtotime() to check for valid dates?


strtotime() doesn't have built-in validation of dates, so if you need it - perform it manually

ps: it is wrong writing date(n,$pickup_time). As long as n is a string - put it within quotes: date('n', $pickup_time)


Should you be able to use strtotime() to check for valid dates?

No, the intent of strtotime()is to do the very best PHP can do in terms of interpreting what date you mean. From the short description on php.net:

Parse about any English textual datetime description into a Unix timestamp

If your string makes no sense, strtotime() will still parse it. Sometimes it comes out garbage, but that's really on how you accept input from users.


You can convert the string to a date and then format it as a string that matches the format you've read in. If the strings don't match, then the date was invalid.

For example:

$str = '10:24 AM 22-Sep';
$d = new DateTime($str);
if ($d->format('H:i A j-M') != $str) {
    echo 'Date is invalid';
}

You'd need to convert the code to use the non-object version date functions. However, this only works if you're expecting a certain format.

Sorry about the edits. This is my first post.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜