복붙노트

두 날짜 비교

PHP

두 날짜 비교

PHP에서 두 날짜를 비교하려면 어떻게해야합니까?

데이터베이스에서 날짜는 2011-10-2과 같습니다.

오늘 날짜를 데이터베이스의 날짜와 비교하여 어느 것이 더 큰지 확인하려면 어떻게해야합니까?

나는 이것을 시험해 보았다.

$today = date("Y-m-d");
$expire = $row->expireDate //from db

if($today < $expireDate) { //do something; }

그러나 그것은 실제로 그렇게 작동하지 않습니다. 그것을하는 또 다른 방법은 무엇입니까?

업데이트 : 나는이 게시물이 좀 오래된 것을 알고 있지만 laravel과 함께 사용되지만 고전적인 PHP에서 사용할 수있는 클래스 인 carbon에 대해 언급하고 싶습니다. 날짜가있는 경이를 수행합니다. 그것을 확인하십시오 : 탄소

해결법

  1. ==============================

    1.YYYY-MM-DD로 저장하면 '1'> '0'등으로 문자열 비교가 가능합니다.

    YYYY-MM-DD로 저장하면 '1'> '0'등으로 문자열 비교가 가능합니다.

  2. ==============================

    2.모든 날짜가 1970 년 1 월 1 일 이후이면, 다음과 같이 사용할 수 있습니다.

    모든 날짜가 1970 년 1 월 1 일 이후이면, 다음과 같이 사용할 수 있습니다.

    $today = date("Y-m-d");
    $expire = $row->expireDate; //from database
    
    $today_time = strtotime($today);
    $expire_time = strtotime($expire);
    
    if ($expire_time < $today_time) { /* do Something */ }
    

    PHP 5> = 5.2.0을 사용하는 경우 DateTime 클래스를 사용할 수 있습니다.

    $today_dt = new DateTime($today);
    $expire_dt = new DateTime($expire);
    
    if ($expire_dt < $today_dt) { /* Do something */ }
    

    아니면이 라인을 따라 뭔가.

  3. ==============================

    3.이미 주어진 답변을 보완하기 위해 다음 예제를 참조하십시오.

    이미 주어진 답변을 보완하기 위해 다음 예제를 참조하십시오.

    $today = new DateTime('');
    $expireDate = new DateTime($row->expireDate); //from database
    
    
    
     if($today->format("Y-m-d") < $expireDate->format("Y-m-d")) { 
           //do something; 
        }
    

    최신 정보:     또는 old-school date () 함수를 간단히 사용하십시오.

    if(date('Y-m-d') < date('Y-m-d', strtotime($expire_date))){
      //echo not yet expired! 
    }   
    
  4. ==============================

    4.나는 PHP로 이것을하지 않을 것이다. 데이터베이스는 오늘 무슨 요일인지 알고 있어야합니다 (예 : MySQL-> NOW () 사용). 쿼리 내에서 비교하고 결과를 반환하며 사용 된 날짜 유형에 따라 아무런 문제가 없습니다.

    나는 PHP로 이것을하지 않을 것이다. 데이터베이스는 오늘 무슨 요일인지 알고 있어야합니다 (예 : MySQL-> NOW () 사용). 쿼리 내에서 비교하고 결과를 반환하며 사용 된 날짜 유형에 따라 아무런 문제가 없습니다.

    SELECT IF(expireDate < NOW(),TRUE,FALSE) as isExpired FROM tableName
    
  5. ==============================

    5.

    $today = date('Y-m-d');//Y-m-d H:i:s
    $expireDate = new DateTime($row->expireDate);// From db 
    $date1=date_create($today);
    $date2=date_create($expireDate->format('Y-m-d'));
    $diff=date_diff($date1,$date2);
    $timeDiff = $diff->format("%R%a days");
    
    echo $timeDiff;
    if($timeDiff < 0){
        echo "Expired.";
    }else{
        echo "Not expired.";
    }
    
  6. ==============================

    6.

    $today_date=date("Y-m-d");
    $entered_date=$_POST['date'];
    $dateTimestamp1 = strtotime($today_date);
    $dateTimestamp2 = strtotime($entered_date);
    $diff= $dateTimestamp1-$dateTimestamp2;
    //echo $diff;
    if ($diff<=0)
       {
         echo "Enter a valid date";
       }
    
  7. ==============================

    7.다음은 분 단위로 두 날짜의 차이를 구하는 방법입니다.

    다음은 분 단위로 두 날짜의 차이를 구하는 방법입니다.

    // set dates
    $date_compare1= date("d-m-Y h:i:s a", strtotime($date1));
    // date now
    $date_compare2= date("d-m-Y h:i:s a", strtotime($date2));
    
    // calculate the difference
    $difference = strtotime($date_compare1) - strtotime($date_compare2);
    $difference_in_minutes = $difference / 60;
    
    echo $difference_in_minutes;
    
  8. ==============================

    8.간단한 PHP를 사용하여 날짜를 비교할 수 있습니다.

    간단한 PHP를 사용하여 날짜를 비교할 수 있습니다.

    $date = new simpleDate();
    echo $date->now()->compare($expire_date)->isBeforeOrEqual();
    

    이것은 당신에게 진실 또는 거짓을 줄 것입니다.

    더 많은 예제를 보려면 자습서를 확인하십시오. 여기를 클릭하십시오.

  9. ==============================

    9.그 문제도 있었고 다음과 같이 해결했습니다.

    그 문제도 있었고 다음과 같이 해결했습니다.

    $today = date("Ymd");
    $expire = str_replace('-', '', $row->expireDate); //from db
    
    if(($today - $expire) > $NUMBER_OF_DAYS) 
    { 
        //do something; 
    }
    
  10. ==============================

    10.VipDomaine 블로그에 대한 답변을 찾았으며 간단합니다.

    VipDomaine 블로그에 대한 답변을 찾았으며 간단합니다.

    strtotime(date("Y"."-01-01")) -strtotime($newdate))/86400
    

    그리고 당신은 2 개의 날짜 사이에서 일을 얻을 것이다.

  11. ==============================

    11.간단히 .. 확인할 수 있습니다.

    간단히 .. 확인할 수 있습니다.

    if ($startdate < $date) {// do something} 
    if ($startdate > $date) {// do something}
    

    두 날짜 모두 같은 형식이어야합니다.

    기타

  12. ==============================

    12.

        while ($row=mysql_fetch_array($result))
        {
    
    
            $orderdate=explode('-',$row['alertdate']);
            $date=$orderdate[0];
            $month=$orderdate[1];
            $year=$orderdate[2];
    
            if((date(Y)>=$year) and (date(m)>=$month) and (date(d)>=$date))
            {
              //write your true code  
    
            }
            else
            {
              //write your false code 
            }
    
  13. ==============================

    13.먼저 서버의 현재 날짜 시간에 원하는 형식을 지정하십시오.

    먼저 서버의 현재 날짜 시간에 원하는 형식을 지정하십시오.

    $ current_date_only = $ current_date [year]. '. $ current_date [mon].' '. $ current_date [mday]; $ current_time_only = $ current_date [ 'hours']. ':'. $ current_date [ 'minutes']. ':'. $ current_date [ 'seconds'];

    도움이되기를 바랍니다.

  14. from https://stackoverflow.com/questions/3847736/comparing-two-dates by cc-by-sa and MIT license