【问题标题】:How to process insane date inputs with php如何使用 php 处理疯狂的日期输入
【发布时间】:2022-01-26 15:41:14
【问题描述】:

我在 php 中有一个代码,用于处理一个人的个人详细信息。我需要代码来处理日期输入,这样当用户输入像 1900 这样的年份时,程序会输出 这是不可能的。如果日期输入在未来,我已成功处理程序应如何响应。 该程序以 欧洲日期格式 获取用户输入的日期,例如 21-10-1990, Am很难处理这个问题,因为 php 内置函数 time() 返回自 1970 年 1 月 1 日以来测量的 unix 时间戳/em>。有没有办法可以绕过这一点来实现从 1900 年及以下开始的年份的检测,而无需直接将条件结构应用于年份?

代码

<?php 

class User{
    //initialize the user properties
    public string $name="";
    public string $dob="";
    public string $national_id="";
    public string $tel="";
    public string $email="";
    public function User($user_name,$dob,$national_id,$tel,$mail){
        //assign the values inside the constructor
        $this->name=$user_name;
        $this->dob=$dob;
        $this->national_id=$national_id;
        $this->tel=$tel;
        $this->email=$mail;
    }
    function validate_dob(){
    
    
        //get a new time in millis from the date passed in
        
        $date_obj=strtotime($this->dob);
        //add conditional structures to make sure the date is not in the 
        //future and is within acceptable time range
        //get the current time from the unix timestamp
        $current_time=time();
        if($date_obj>$current_time){
            echo "\n";
            echo "That is impossible, you birth date cannot be in the future";
        }
        //if the date is also 1900 and below then also throw an error, i need help here

    }
}

【问题讨论】:

  • 我强烈推荐使用 PHP 的 DateTimephp.net/manual/en/class.datetime.php,而不是 time()strtotime()
  • 它适用于处理未来的出生日期,我只是想让它适用于疯狂的日期时间,如 1900、1899 等等,我愿意通过上述课程的答案提出建议
  • 使用IntlCalendar
  • 如果您使用&gt; 处理未来的日期,您可以使用&lt; 处理过去的日期。 UTC 时间 1900-01-01 午夜的 Unix 时间是 -2208988800。我对这里提出的确切问题有点困惑,因为你提到了很多不同的事情。

标签: php date


【解决方案1】:

使用DateTime 代替time()strtotime()

$date_obj = DateTime::createFromFormat('d-m-Y',$this->dob);
$current_time = new DateTime('NOW');
$date1900 = DateTime::createFromFormat('d-m-Y','01-01-1900');

if($date_obj > $current_time){
    echo "\n";
    echo "That is impossible, your birth date cannot be in the future";
}else
if($date_obj < $date1900){
    echo "\n";
    echo "That is impossible, your birth date cannot before the year 1900";
}

【讨论】:

    【解决方案2】:

    使用日期时间()

    $date1   =   date('d-m-Y',strtotime($this->dob));
    $date2   =   date('d-m-Y',strtotime(time());
    
    $d1 = new DateTime($date1);
    $d2 = new DateTime($date2); 
    if($date1 >$date2 ){
         echo "\n";
       echo "That is impossible, you birth date cannot be in the future";
    }
    

    【讨论】:

      猜你喜欢
      • 2013-12-18
      • 2013-02-12
      • 1970-01-01
      • 1970-01-01
      • 2014-04-19
      • 2014-04-25
      • 2014-09-17
      • 1970-01-01
      • 2010-12-12
      相关资源
      最近更新 更多