dqqvravff05370501 2013-05-01 16:24
浏览 63

使用DateTime :: createFromFormat验证Year

I have this block of code for validating a correctly formatted date prior to submission to a DB insert using DateTime::createFromFormat(). I'm expecting the date format to convert 'DD/MM/YYYY' to 'YYYY-MM-DD' or else raise an error.

$dateofbirth = trim($_POST['dateofbirth']);
$date = DateTime::createFromFormat('d/m/Y', $dateofbirth);

$date_errors = DateTime::getLastErrors();
    var_dump($date_errors);
if ($date_errors['warning_count'] + $date_errors['error_count'] > 0) {
    $dobError = 'Date '.$dateofbirth.' is not a valid DD/MM/YYYY format.';
    $hasError = true;
} else {
    $mysql_dob = $date->format('Y-m-d');
}
error_log($dateofbirth.' -> '.$mysql_dob);

This date works

 $dateofbirth = '30/11/1980'; => 1980-11-30

but this one fail silently

 $dateofbirth = '30/11/80'; => 0080-11-30

since i'm expecting to be notified of the missing century digits. I've read the formatting rules and am using the upper case 'Y' which should ensure a 4 digit year. Any idea's where i'm going wrong?

EDIT

1 - Correct the test date as per OneTrickPony's comment

2 - I added a var_dump of the $date_errors variable. Since the format is 'd/m/Y' and the input is '30/11/80' i am expecting an error or warning but i don't get one.

array(4) {
  ["warning_count"]=>
  int(0)
  ["warnings"]=>
  array(0) {
  }
  ["error_count"]=>
  int(0)
  ["errors"]=>
  array(0) {
  }
}
30/11/80 -> 0080-11-30
  • 写回答

2条回答 默认 最新

  • douzhang2092 2013-05-01 16:30
    关注

    From the documentation for DateTime::createFromFormat

    http://www.php.net/manual/en/datetime.createfromformat.php

    Returns a new DateTime instance or FALSE on failure.
    

    So rather than checking getLastErrors you should check if $date === false

    Change your error check to:

    if ($date === false) {
        $dobError = 'Date '.$dateofbirth.' is not a valid DD/MM/YYYY format.';
        $hasError = true;
    } else {
        $mysql_dob = $date->format('Y-m-d');
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答