Correctly determine if date string is a valid date in that format

前端 未结 16 2485
名媛妹妹
名媛妹妹 2020-11-22 17:02

I\'m receiving a date string from an API, and it is formatted as yyyy-mm-dd.

I am currently using a regex to validate the string format, which works ok,

16条回答
  •  佛祖请我去吃肉
    2020-11-22 18:07

    Give this a try:

    $date = "2017-10-01";
    
    
    function date_checker($input,$devider){
      $output = false;
    
      $input = explode($devider, $input);
      $year = $input[0];
      $month = $input[1];
      $day = $input[2];
    
      if (is_numeric($year) && is_numeric($month) && is_numeric($day)) {
        if (strlen($year) == 4 && strlen($month) == 2 && strlen($day) == 2) {
          $output = true;
        }
      }
      return $output;
    }
    
    if (date_checker($date, '-')) {
      echo "The function is working";
    }else {
      echo "The function isNOT working";
    }
    

提交回复
热议问题