0

I have a date in the format of "14/11/2012 4:26:10 PM" pulled from a mysql query.

I'm not very experienced with PHP, but how can i calculate a simple timespan between dates "Then" and "Now"?

And format it in a human readable string? for example... "1hour, 5 minutes ago".

I've tried to search for a solution and i found one that i thought worked but it didn't account for the AM/PM so it ended up causing a problem when i converted it to a time stamp. does anyone have any idea?

This is what i am trying to do but this does not work so well:

$time = $row["NotificationSent"];           
            list($day, $month, $year, $hour, $minute) = split('[/ :]', $time); 
            $timestamp = mktime($hour, $minute,0, $month, $day, $year);         
            $j = TimeSince($timestamp);

the timesince function i found off google that I'm using is:

    function TimeSince($original) // $original should be the original date and time in Unix format
    {
        // Common time periods as an array of arrays
        $periods = array(
            array(60 * 60 * 24 * 365 , 'year'),
            array(60 * 60 * 24 * 30 , 'month'),
            array(60 * 60 * 24 * 7, 'week'),
            array(60 * 60 * 24 , 'day'),
            array(60 * 60 , 'hour'),
            array(60 , 'minute'),
            );

        $today = time();
        $since = $today - $original; // Find the difference of time between now and the past

        // Loop around the periods, starting with the biggest
        for ($i = 0, $j = count($periods); $i < $j; $i++)
        {
            $seconds = $periods[$i][0];
            $name = $periods[$i][1];

            // Find the biggest whole period
            if (($count = floor($since / $seconds)) != 0)
            {
                break;
            }
        }

        $output = ($count == 1) ? '1 '.$name : "$count {$name}s";

        if ($i + 1 < $j)
        {
            // Retrieving the second relevant period
            $seconds2 = $periods[$i + 1][0];
            $name2 = $periods[$i + 1][1];

            // Only show it if it's greater than 0
            if (($count2 = floor(($since - ($seconds * $count)) / $seconds2)) != 0)
            {
                $output .= ($count2 == 1) ? ', 1 '.$name2 : ", $count2 {$name2}s";
            }
        }
        return $output;
    }

The returned result is formatted to what I'm looking for but is giving incorrect numbers. "19/11/2012 2:48:53 PM" is returning "1 day, 5 hours" but it should be "17 hrs, 32 mins"

Any help is appreciated.

4

2 回答 2

4

看,这就是DateTime对象来救援的地方:

<?php

$time = DateTime::createFromFormat("d/m/Y g:i:s A", "14/11/2012 4:26:10 PM");;
$now = new DateTime;

$diff = $time->diff($now);
var_dump($diff);

你得到了准确的区别,你可以用你喜欢的任何方式格式化它。

于 2012-11-19T22:30:55.200 回答
1

如果您有人类可读的时间戳,则可以使用strtotime()将其转换为 unix 时间戳:

http://php.net/manual/en/function.strtotime.php

然后只需从该值中减去time()即可获得过去的时间(以秒为单位)。

于 2012-11-19T22:29:33.093 回答