douyong1886 2015-07-23 13:36
浏览 65
已采纳

验证2日期以确保它们是有效日期

I am working with a date which is formatted like so:

25/02/1994 - 15/03/2000

To get each date I am using the explode function to separate each date between dash

$newdate = explode("-",$olddate);

Now my problem is, if it was just one date I could split it up in to 3 parts, the day, month, year and use the checkdate function to validate the month, but because I am using explode I cannot split it up like that (to my knowledge)

What would be the best way to validate the date for legitimacy?

  • 写回答

2条回答 默认 最新

  • dongsao8279 2015-07-23 13:55
    关注

    You have a good start, after you exploded your string by -, just simply loop through each date with array_reduce() and reduce it to 1 value.

    In the anonymous function you just explode() each date and check with checkdate() if it is a valid date, e.g.

    <?php
    
        $str = "25/02/1994 - 15/03/2000";
        $dates = explode("-", $str);
    
        if(array_reduce($dates, function($keep, $date){
            list($day, $month, $year) = array_map("trim",explode("/", $date));
            if(!checkdate($month, $day, $year))
                return $keep = FALSE;
            return $keep;
        }, TRUE)) {
            echo "all valid dates";
        }
    
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?