PHP Check if date is past to a certain date given in a certain format

后端 未结 4 1732
温柔的废话
温柔的废话 2020-12-14 14:40

I have a php event\'s calender which queries the database to get the dates.

I display the event date using:

$event[\'date\']

and t

相关标签:
4条回答
  • 2020-12-14 15:14

    You can use strtotime() and time():

    if (strtotime($event['date']) < time()) {
        // past date
    }
    
    0 讨论(0)
  • 2020-12-14 15:26

    @Satch3000 You've accepted the wrong answer as a right solution ( @Amal Murali )

    Please see the output, Here I input the today date but it returns current date as past date.

    <?php
    
    /* Enter today date */
    $date = new DateTime("09/14/2017");
    $now = new DateTime();
    
    print_r($date);
    
    print_r($now);
    
    
    if($date < $now) {
        echo 'date is in the past';
    }
    

    Output will be

    DateTime Object
    (
        [date] => 2017-09-14 00:00:00.000000
        [timezone_type] => 3
        [timezone] => UTC
    )
    DateTime Object
    (
        [date] => 2017-09-14 07:12:52.000000
        [timezone_type] => 3
        [timezone] => UTC
    )
    date is in the past
    

    Solution

    $Date1 = strtotime(date('Y-m-d', strtotime('2017-09-15') ) ).' ';
    $Date2 = strtotime(date('Y-m-d'));
    
      if($Date1 < $Date2) {
            echo 'date is in the past';
        }
    
    0 讨论(0)
  • 2020-12-14 15:35
    if (time() > strtotime($event['date']))
    {
        // current date is greater than 2013-07-31 
    }
    

    strtotime parses the date sting using these rules.

    0 讨论(0)
  • 2020-12-14 15:40

    You can compare the dates with PHP's DateTime class:

    $date = new DateTime($event['date']);
    $now = new DateTime();
    
    if($date < $now) {
        echo 'date is in the past';
    }
    

    See it live!


    Note: Using DateTime class is preferred over strtotime() since the latter will only work for dates before 2038. Read more about the Year_2038_problem.

    0 讨论(0)
提交回复
热议问题