Compare given date with today

前端 未结 13 2025
别那么骄傲
别那么骄傲 2020-11-22 16:22

I have following

$var = \"2010-01-21 00:00:00.0\"

I\'d like to compare this date against today\'s date (i.e. I\'d like to know if this

相关标签:
13条回答
  • 2020-11-22 16:48

    Some given answers don't have in consideration the current day!

    Here it is my proposal.

    $var = "2010-01-21 00:00:00.0"
    $given_date = new \DateTime($var);
    
    if ($given_date == new \DateTime('today')) {
      //today
    }
    
    if ($given_date < new \DateTime('today')) {
      //past
    }
    
    if ($given_date > new \DateTime('today')) {
      //future
    }
    
    0 讨论(0)
  • 2020-11-22 16:51

    Here you go:

    function isToday($time) // midnight second
    {
        return (strtotime($time) === strtotime('today'));
    }
    
    isToday('2010-01-22 00:00:00.0'); // true
    

    Also, some more helper functions:

    function isPast($time)
    {
        return (strtotime($time) < time());
    }
    
    function isFuture($time)
    {
        return (strtotime($time) > time());
    }
    
    0 讨论(0)
  • 2020-11-22 16:53

    If you do things with time and dates Carbon is you best friend;

    Install the package then:

    $theDay = Carbon::make("2010-01-21 00:00:00.0");
    
    $theDay->isToday();
    $theDay->isPast();
    $theDay->isFuture();
    if($theDay->lt(Carbon::today()) || $theDay->gt(Carbon::today()))
    

    lt = less than, gt = greater than

    As in the question:

    $theDay->gt(Carbon::today()) ? true : false;
    

    and much more;

    0 讨论(0)
  • 2020-11-22 16:55

    Compare date time objects:

    (I picked 10 days - Anything older than 10 days is "OLD", else "NEW")

    $now   = new DateTime();
    $diff=date_diff($yourdate,$now);
    $diff_days = $diff->format("%a");
    if($diff_days > 10){
        echo "OLD! " . $yourdate->format('m/d/Y');
    }else{
        echo "NEW! " . $yourdate->format('m/d/Y');
    }
    
    0 讨论(0)
  • 2020-11-22 16:58

    To complete BoBby Jack, the use of DateTime OBject, if you have php 5.2.2+ :

    if(new DateTime() > new DateTime($var)){
        // $var is before today so use it
    
    }
    
    0 讨论(0)
  • 2020-11-22 17:02

    Expanding on Josua's answer from w3schools:

    //create objects for the dates to compare
    $date1=date_create($someDate);
    $date2=date_create(date("Y-m-d"));
    $diff=date_diff($date1,$date2);
    //now convert the $diff object to type integer
    $intDiff = $diff->format("%R%a");
    $intDiff = intval($intDiff);
    //now compare the two dates
    if ($intDiff > 0)  {echo '$date1 is in the past';}
    else {echo 'date1 is today or in the future';}
    

    I hope this helps. My first post on stackoverflow!

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