function that formats the time difference

后端 未结 2 942
失恋的感觉
失恋的感觉 2020-12-20 03:35

I am trying to create a function that compares a date with the current time, and returns a nicely formatted string.
I have written some code in haste and it works, but I

相关标签:
2条回答
  • 2020-12-20 04:20

    I'd recommend doing it in javascript. You can use the TimeAgo plugin for jquery. The cool thing about this is it will update in realtime on the client side without any page refresh. This is dead simple to use, and fits your requirements.

    0 讨论(0)
  • 2020-12-20 04:37

    Some code I use and it's never failed, just put the Unix timestamp in, if you use a second argument in the function that can be the "to" condition

    echo timeDiffrence('1300392875');
    
    function timeDiffrence($from, $to = null){
        $to = (($to === null) ? (time()) : ($to));
        $to = ((is_int($to)) ? ($to) : (strtotime($to)));
        $from = ((is_int($from)) ? ($from) : (strtotime($from)));
        $units = array
        (
        "y"   => 29030400, // seconds in a year   (12 months)
        "month"  => 2419200,  // seconds in a month  (4 weeks)
        "w"   => 604800,   // seconds in a week   (7 days)
        "d"    => 86400,    // seconds in a day    (24 hours)
        "h"   => 3600,     // seconds in an hour  (60 minutes)
        "m" => 60,       // seconds in a minute (60 seconds)
        "s" => 1         // 1 second
        );
        $diff = abs($from - $to);
        $suffix = (($from > $to) ? ("from now") : ("ago"));
        foreach($units as $unit => $mult)
        if($diff >= $mult)
        {
            //$and = (($mult != 1) ? ("") : ("and "));
            $output .= "".$and.intval($diff / $mult)."".$unit.((intval($diff / $mult) == 1) ? ("") : (""));
            $diff -= intval($diff / $mult) * $mult;
        }
        $output .= " ".$suffix;
        $output = substr($output, strlen(""));
        if($output =='go' || $output ==' ago'){$output = 'A few secs ago';}
        return $output;
    }
    
    0 讨论(0)
提交回复
热议问题