php function to convert Unix timestamp into minutes or hours or days like digg?

后端 未结 3 664
礼貌的吻别
礼貌的吻别 2021-01-16 02:37

i want a php function to convert a unix time stamp to like this:

15 seconds

or

45 minutes

or

3 hours

and not like this : 2sec

相关标签:
3条回答
  • 2021-01-16 03:22

    PHP doesn't have a built-in function to do it for you, so you'd have to do it by hand. This function will get the difference in days, hours, minutes, or seconds and return in the format 'X days/hours/minutes/seconds':

    <?php
    function GetTimeDiff($timestamp) {
        $how_log_ago = '';
        $seconds = time() - $timestamp; 
        $minutes = (int)($seconds / 60);
        $hours = (int)($minutes / 60);
        $days = (int)($hours / 24);
        if ($days >= 1) {
          $how_log_ago = $days . ' day' . ($days != 1 ? 's' : '');
        } else if ($hours >= 1) {
          $how_log_ago = $hours . ' hour' . ($hours != 1 ? 's' : '');
        } else if ($minutes >= 1) {
          $how_log_ago = $minutes . ' minute' . ($minutes != 1 ? 's' : '');
        } else {
          $how_log_ago = $seconds . ' second' . ($seconds != 1 ? 's' : '');
        }
        return $how_log_ago;
    ?>
    
    0 讨论(0)
  • 2021-01-16 03:28

    If this is for a website, you might consider Timeago. Otherwise the algorithm is pretty straightforward. Something like:

    $diff = $date - $now;
    if ($diff > 2 * ONE_YEAR)
        return sprintf("%d years", round($diff / ONE_YEAR));
    else if ($diff > ONE_YEAR)
        return "1 year";
    else if ($diff > 2 * ONE_MONTH)
        return sprintf("%d months", round($diff / ONE_MONTH));
    ...etc...
    
    0 讨论(0)
  • 2021-01-16 03:29

    Try this:

    function toFriendlyTime($seconds) {
      $measures = array(
        'day'=>24*60*60,
        'hour'=>60*60,
        'minute'=>60,
        'second'=>1,
        );
      foreach ($measures as $label=>$amount) {
        if ($seconds >= $amount) {  
          $howMany = floor($seconds / $amount);
          return $howMany." ".$label.($howMany > 1 ? "s" : "");
        }
      } 
      return "now";
    }   
    

    As you can see, it's also flexible for adding/removing measures of time as you see fit. Just be sure to order the measures from largest to smallest. A test:

    print(                           
        toFriendlyTime(0)."\n"           
        .toFriendlyTime(1)."\n"          
        .toFriendlyTime(2)."\n"          
        .toFriendlyTime(60)."\n"         
        .toFriendlyTime(3600)."\n"   
        .toFriendlyTime(24*3600)."\n"                                               
        );
    

    Results in:

    now
    1 second
    2 seconds
    1 minute
    1 hour
    1 day
    
    0 讨论(0)
提交回复
热议问题