Today or Yesterday from date

Discussion in 'PHP' started by tobydawson13, Jul 9, 2010.

  1. #1
    Hi guys, could somebody tell me if there is a better way of finding out if a date is "Today" or "Yesterday"? Is there anyway to shorten/speed up the code I already have?

    Thanks :)

    $time = $rows['date'];
    
    $lastday = date('m/d/Y',$time);
    
    $today = mktime(0,0,0,date("m"),date("d"),date("Y"));
    $yesterday = mktime(0,0,0,date("m"),date("d")-1,date("Y"));
    $today = date("m/d/Y", $today);
    $yesterday = date("m/d/Y", $yesterday);
    
    if($today == $lastday){$dateposted="Today";}
    elseif($yesterday == $lastday) {$dateposted="Yesterday";}
    else {$dateposted = $lastday;}
    
    echo $dateposted;
    PHP:
     
    tobydawson13, Jul 9, 2010 IP
  2. flexdex

    flexdex Peon

    Messages:
    104
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    0
    #2
    if you have access to php 5.3 the answer is yes.

    Please refer to:

    http://de3.php.net/manual/en/class.datetime.php
    http://de3.php.net/manual/en/datetime.sub.php


    10 days to past:
    Object oriented style
    
    <?php
    $date = new DateTime('2000-01-20');
    $date->sub(new DateInterval('P10D'));
    echo $date->format('Y-m-d') . "\n";
    ?>
    
    PHP:
    Procedural style
    
    <?php
    $date = date_create('2000-01-20');
    date_sub($date, date_interval_create_from_date_string('10 days'));
    echo date_format($date, 'Y-m-d');
    ?>
    
    PHP:
     
    flexdex, Jul 9, 2010 IP
  3. tobydawson13

    tobydawson13 Active Member

    Messages:
    645
    Likes Received:
    5
    Best Answers:
    0
    Trophy Points:
    60
    #3
    Ok thanks, but do you think that will work better than my original code?
     
    tobydawson13, Jul 9, 2010 IP
  4. tobydawson13

    tobydawson13 Active Member

    Messages:
    645
    Likes Received:
    5
    Best Answers:
    0
    Trophy Points:
    60
    #4
    Turns out I don't have php 5.3, I have php 5.2.13. Is there another code I could use instead?
     
    tobydawson13, Jul 9, 2010 IP
  5. danx10

    danx10 Peon

    Messages:
    1,179
    Likes Received:
    44
    Best Answers:
    2
    Trophy Points:
    0
    #5
    $time = $rows['date'];
    
    $lastday = date('m/d/Y', $time);
    
    $today = strtotime("today");
    $yesterday = strtotime("yesterday");
    $today = date("m/d/Y", $today);
    $yesterday = date("m/d/Y", $yesterday);
    
    if ($today == $lastday) {
    $dateposted = "Today";
    } elseif ($yesterday == $lastday) {
    $dateposted = "Yesterday";
    } else {
    $dateposted = $lastday;
    }
    
    echo $dateposted;
    PHP:
     
    danx10, Jul 9, 2010 IP
  6. largn81

    largn81 Peon

    Messages:
    237
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #6
    PHP 6 is coming it s more user friendly....
     
    largn81, Jul 10, 2010 IP