开发者

How to check if a variable contains a date or a date and text?

How to check whether a variable $date c开发者_开发知识库ontains a date in the form of 2011-09-20 ? This is to know if the $date contains any letters in it because I want to use the date() and gives me error.


try this:

$date = '2011-09-20';
list($y, $m, $d) = explode("-", $date);
if(checkdate($m, $d, $y)){
    echo "OK Date";
} else {
    echo "BAD Date";
}

demo here: http://codepad.org/3iqrQrey


One approch would be this though it's not perfect.

if (false === strtotime($date)) {
    echo 'invalid date';
else {
    echo 'valid date';
}


This is not exatly what you ask for (will also accept other date formats) but will help to find out date is valid:
strtotime($date) will return FALSE if $date has invalid date format.
Manual


Maybe it helps if you try the is_numeric() in combination with the str_replace() method, like so:

<?php
  $isValid = is_numeric(str_replace('-', '', $myDateToCheck));
?>

Of course, this does not say anything about the format of the date but is does give an indication whether the variable contains any non-numeric characters.

If the above example returns true, you might want to use the checkdate() method to further investigate your variable.


You could use a regular expression (^[1-9]{4}-[1-9]{2}-[1-9]{2}$) with preg_match for this.

Another way would be strptime, which is used to convert a string (associated with a certain format) to a time.


SOLUTION 1

Combining what @Alfwed and @JellyBelly wrote, here's how I did it:

public function valid_date($inputdate){
    $date = $inputdate;
    if (strtotime($date)){
       if (strpos($date,'/') !== false) {
         list($day, $month, $year) = explode('/', $date);
         return checkdate($month, $day, $year);
       }else{
            return false;
       }
    }else{
        return false;
    }
}

It will check wether if the input is text (e.g: "adasdsad"), or if it has a date format (e.g: "10/02/1988"), and it checks if it's a valid date.

If input date is 10-10-1996 which is also a valid format, or 10.02.1996, it won't accept them because I'm asking the user to use the format with "/". Just remove the if it if you don't want to do this validation and that is it.

SOLUTION 2

I have found that solution 1 doesn't work if you plan to enter a future date. So I had to find another solution. Here it is:

    public function valid_date($date, $format = 'd/m/Y'){
        $d = DateTime::createFromFormat($format, $date);
        return $d && $d->format($format) == $date;
}

It's not mine, found it at: link

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜