We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Time Calculation

Hi,

I noticed a peculiar issue when I transferred my website from localhost to my server. The search time calculation I have is having issues on the server that are not visual or apparent on localhost. Here is a picture of the issue below.

Picture

Here are the relevant pieces of code associated with that sidebar.

Please note the time format in the database is formatted as 2018-02-14 01:32:25 with the timestamp type.

The following is the variable I pass from my controller to the view in order to grab the information from my table.

$this->view->recent = Searches::findFirst(["order" => "date_searched DESC"]);

Here is the snippet of code that is used inside the template of said page.

{{ elapsed(search.date_searched | strtotime) }}

elapsed function

public static function time_elapsed_string( $ptime ) {
        $etime = time() - $ptime;

        if ( $etime < 1 ) {
            return '0 seconds - '.$etime;
        }

        $a = array(
            12 * 30 * 24 * 60 * 60 => 'year', 30 * 24 * 60 * 60 => 'month', 24 * 60 * 60 => 'day', 60 * 60 => 'hour', 60 => 'minute', 1 => 'second'
        );

        foreach ( $a as $secs => $str ) {
            $d = $etime / $secs;
            if ( $d >= 1 ) {
                $r = round( $d );
                return $r . ' ' . $str . ( $r > 1 ? 's' : '' ) . ' ago';
            }
        }
    }


77.7k
Accepted
answer

Make sure your db and php are all in the same timezone



3.7k
edited Feb '18

You're right! It was an error on my end which I failed to see at first, but I have it resolved now :)

Slightly off-topic, but I recommend you look into DateTime::diff() to make it much simpler to calculate the date difference. This method also takes into account Daylight Saving Time.

https://www.php.net/manual/en/datetime.diff.php