Changeset 760 for branches/1.1dev/lib


Ignore:
Timestamp:
Feb 10, 2022 3:48:07 AM (2 years ago)
Author:
anonymous
Message:

Add humanTime() function

File:
1 edited

Legend:

Unmodified
Added
Removed
  • branches/1.1dev/lib/Utilities.inc.php

    r759 r760  
    411411}
    412412
     413/*
     414* Returns a human readable amount of time for the given amount of seconds.
     415*
     416* 45 seconds
     417* 12 minutes
     418* 3.5 hours
     419* 2 days
     420* 1 week
     421* 4 months
     422*
     423* Months are calculated using the real number of days in a year: 365.2422 / 12.
     424*
     425* @access   public
     426* @param    int $seconds Seconds of time.
     427* @param    string $max_unit Key value from the $units array.
     428* @param    string $format Sprintf formatting string.
     429* @return   string Value of units elapsed.
     430* @author   Quinn Comendant <quinn@strangecode.com>
     431* @version  1.0
     432* @since    23 Jun 2006 12:15:19
     433*/
     434function humanTime($seconds, $max_unit=null, $format='%01.1f')
     435{
     436    // Units: array of seconds in the unit, singular and plural unit names.
     437    $units = array(
     438        'second' => array(1, _("second"), _("seconds")),
     439        'minute' => array(60, _("minute"), _("minutes")),
     440        'hour' => array(3600, _("hour"), _("hours")),
     441        'day' => array(86400, _("day"), _("days")),
     442        'week' => array(604800, _("week"), _("weeks")),
     443        'month' => array(2629743.84, _("month"), _("months")),
     444        'year' => array(31556926.08, _("year"), _("years")),
     445        'decade' => array(315569260.8, _("decade"), _("decades")),
     446        'century' => array(3155692608, _("century"), _("centuries")),
     447    );
     448
     449    // Max unit to calculate.
     450    $max_unit = isset($units[$max_unit]) ? $max_unit : 'year';
     451
     452    $final_time = $seconds;
     453    $final_unit = 'second';
     454    foreach ($units as $k => $v) {
     455        if ($seconds >= $v[0]) {
     456            $final_time = $seconds / $v[0];
     457            $final_unit = $k;
     458        }
     459        if ($max_unit == $final_unit) {
     460            break;
     461        }
     462    }
     463    $final_time = sprintf($format, $final_time);
     464    return sprintf('%s %s', $final_time, (1 == $final_time ? $units[$final_unit][1] : $units[$final_unit][2]));
     465}
     466
    413467/**
    414468 * If $var is net set or null, set it to $default. Otherwise leave it alone.
Note: See TracChangeset for help on using the changeset viewer.