Can my PHP time difference function be improved?

前端 未结 1 565
栀梦
栀梦 2021-01-03 05:25

Below is my function that will take a timestamp and tell you the time that has passed from now in the format of 23 days 3 hours 4 minutes 6 seconds

<
相关标签:
1条回答
  • 2021-01-03 05:34

    Do take a look at the documentation for the time function at the PHP site. Specially this and this.

    Here is a snippet by Aidan Lister that is similar:

    /**
     * A function for making time periods readable
     *
     * @author      Aidan Lister <aidan@php.net>
     * @version     2.0.0
     * @link        http://aidanlister.com/2004/04/making-time-periods-readable/
     * @param       int     number of seconds elapsed
     * @param       string  which time periods to display
     * @param       bool    whether to show zero time periods
     */
    function time_duration($seconds, $use = null, $zeros = false)
    {
        // Define time periods
        $periods = array (
            'years'     => 31556926,
            'Months'    => 2629743,
            'weeks'     => 604800,
            'days'      => 86400,
            'hours'     => 3600,
            'minutes'   => 60,
            'seconds'   => 1
            );
    
        // Break into periods
        $seconds = (float) $seconds;
        foreach ($periods as $period => $value) {
            if ($use && strpos($use, $period[0]) === false) {
                continue;
            }
            $count = floor($seconds / $value);
            if ($count == 0 && !$zeros) {
                continue;
            }
            $segments[strtolower($period)] = $count;
            $seconds = $seconds % $value;
        }
    
        // Build the string
        foreach ($segments as $key => $value) {
            $segment_name = substr($key, 0, -1);
            $segment = $value . ' ' . $segment_name;
            if ($value != 1) {
                $segment .= 's';
            }
            $array[] = $segment;
        }
    
        $str = implode(', ', $array);
        return $str;
    }
    
    0 讨论(0)
提交回复
热议问题