Changeset 233


Ignore:
Timestamp:
Feb 15, 2007 9:14:39 PM (17 years ago)
Author:
quinn
Message:

Q - added humanTime to Utilities

File:
1 edited

Legend:

Unmodified
Added
Removed
  • tags/2.0.2/lib/Utilities.inc.php

    r222 r233  
    268268
    269269    return sprintf($format, $size, $units[$i]);
     270}
     271
     272/*
     273* Returns a human readable amount of time for the given amount of seconds.
     274*
     275* 45 seconds
     276* 12 minutes
     277* 3.5 hours
     278* 2 days
     279* 1 week
     280* 4 months
     281*
     282* Months are calculated using the real number of days in a year: 365.2422 / 12.
     283*
     284* @access   public
     285* @param    int $seconds Seconds of time.
     286* @param    string $max_unit Key value from the $units array.
     287* @param    string $format Sprintf formatting string.
     288* @return   string Value of units elapsed.
     289* @author   Quinn Comendant <quinn@strangecode.com>
     290* @version  1.0
     291* @since    23 Jun 2006 12:15:19
     292*/
     293function humanTime($seconds, $max_unit=null, $format='%01.1f')
     294{
     295    // Units: array of seconds in the unit, singular and plural unit names.
     296    $units = array(
     297        'second' => array(1, _("second"), _("seconds")),
     298        'minute' => array(60, _("minute"), _("minutes")),
     299        'hour' => array(3600, _("hour"), _("hours")),
     300        'day' => array(86400, _("day"), _("days")),
     301        'week' => array(604800, _("week"), _("weeks")),
     302        'month' => array(2629743.84, _("month"), _("months")),
     303        'year' => array(31556926.08, _("year"), _("years")),
     304        'decade' => array(315569260.8, _("decade"), _("decades")),
     305    );
     306   
     307    // Max unit to calculate.
     308    $max_unit = isset($units[$max_unit]) ? $max_unit : 'decade';
     309
     310    $final_time = $seconds;
     311    $last_unit = 'second';
     312    foreach ($units as $k => $v) {
     313        if ($max_unit != $k && $seconds >= $v[0]) {
     314            $final_time = $seconds / $v[0];
     315            $last_unit = $k;
     316        }
     317    }
     318    $final_time = sprintf($format, $final_time);
     319    return sprintf('%s %s', $final_time, (1 == $final_time ? $units[$last_unit][1] : $units[$last_unit][2]));   
    270320}
    271321
Note: See TracChangeset for help on using the changeset viewer.