PHP: date “Yesterday”, “Today”

后端 未结 9 1763
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-09 10:20

I have a little function that shows latest activity, it grab timestamp in unix format from the db, and then it echo out with this line:

 date(\"G:i:s j M -Y\         


        
相关标签:
9条回答
  • 2020-12-09 11:13

    here's working function

        function minus_one_day($date){
          $date2 = formatDate4db($date);
          $date1 = str_replace('-', '/', $date2);
          $yesterday = date('Y-m-d',strtotime($date1 . "-1 days"));
          return $yesterday; }
    

    hope work for you...

    0 讨论(0)
  • 2020-12-09 11:18

    I would find the timestap for last midnight and the one before it, if $last_access is between the two timestamps, then display yesterday, anything greater than last midnight's timestamp would be today...

    I believe that would be the quicker than doing date arithmetic.

    Actually, I just tested this code and it seems to work great:

    <?php
        if ($last_access >= strtotime("today"))
            echo "Today";
        else if ($last_access >= strtotime("yesterday"))
            echo "Yesterday";
    ?>
    
    0 讨论(0)
  • 2020-12-09 11:20

    I enhanced Thomas Decaux answer to come up with this

    function formatTimeString($timeStamp) {
    $str_time = date("Y-m-d H:i:sP", $timeStamp);
    $time = strtotime($str_time);
    $d = new DateTime($str_time);
    
    $weekDays = ['Mon', 'Tue', 'Wed', 'Thur', 'Fri', 'Sat', 'Sun'];
    $months = ['Jan', 'Feb', 'Mar', 'Apr', ' May', 'Jun', 'Jul', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec'];
    
    if ($time > strtotime('-2 minutes')) {
      return 'Just now';
    } elseif ($time > strtotime('-59 minutes')) {
      $min_diff = floor((strtotime('now') - $time) / 60);
      return $min_diff . ' min' . (($min_diff != 1) ? "s" : "") . ' ago';
    } elseif ($time > strtotime('-23 hours')) {
      $hour_diff = floor((strtotime('now') - $time) / (60 * 60));
      return $hour_diff . ' hour' . (($hour_diff != 1) ? "s" : "") . ' ago';
    } elseif ($time > strtotime('today')) {
      return $d->format('G:i');
    } elseif ($time > strtotime('yesterday')) {
      return 'Yesterday at ' . $d->format('G:i');
    } elseif ($time > strtotime('this week')) {
      return $weekDays[$d->format('N') - 1] . ' at ' . $d->format('G:i');
    } else {
      return $d->format('j') . ' ' . $months[$d->format('n') - 1] .
      (($d->format('Y') != date("Y")) ? $d->format(' Y') : "") .
      ' at ' . $d->format('G:i');
    }
    

    }

    It takes in the time stamp as the argument, it adds the year of the time if it was from a different year, etc...

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