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

后端 未结 3 1267
余生分开走
余生分开走 2021-01-16 03:01

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:13

    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
    

提交回复
热议问题