开发者

strtotime() converts a non existing date to another date

开发者 https://www.devze.com 2023-04-09 15:13 出处:网络
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

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 happe开发者_运维百科n..

$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.


You might look into checkdate.


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');


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.


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()


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


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.

0

精彩评论

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

关注公众号