Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP file modified time use GMT offset setting to report correct time

I'm currently reporting file modified time like so:

$this->newScanData[$key]["modified"] = filemtime($path."/".$file);
$modifiedtime = date($date_format." ".$time_format, $this->newScanData[$key]["modified"]);

To me I thought there was nothing wrong with that but a user of my code is reporting the time being 4 hours out. The only reason why I can think of this is because the server is in a different timezone to the user. Each user has a variable I can use $gmt_offset that stores the time zone that user is in. $gmt_offset is stored as a basic float offset.

The server could be in any timezone, not necessarily in GMT-0. The server might not be in the same timezone as the user.

How do I get $modifiedtime to have the correct time for the user in his timezone based on $gmt_offset?

like image 826
Scott Avatar asked Jan 18 '26 09:01

Scott


2 Answers

filemtime() will return a unix timestamp based on the server's clock. Since you have user to gmt offset available, you must convert the unix timestamp to GMT and then into user's timszone as follows:

<?php
    list($temp_hh, $temp_mm) = explode(':', date('P'));
    $gmt_offset_server = $temp_hh + $temp_mm / 60;
    $gmt_offset_user   = -7.0;
    $timestamp         = filemtime(__FILE__);
    echo sprintf('
        Time based on server time.........: %s
        Time converted to GMT.............: %s
        Time converted to user timezone...: %s
        Auto calculated server timezone...: %s
        ',
        date('Y-m-d h:i:s A', $timestamp),
        date('Y-m-d h:i:s A', $timestamp - $gmt_offset_server * 3600),
        date('Y-m-d h:i:s A', $timestamp - $gmt_offset_server * 3600 + $gmt_offset_user * 3600),
        $gmt_offset_server
    );

    // Output based on server timezone = PKT (+05:00 GMT) and user timezone = PDT (-07:00 GMT)
    // Time based on server time.........: 2011-06-09 03:54:38 PM
    // Time converted to GMT.............: 2011-06-09 10:54:38 AM
    // Time converted to user timezone...: 2011-06-09 03:54:38 AM
    // Auto calculated server timezone...: 5
like image 128
Salman A Avatar answered Jan 19 '26 21:01

Salman A


What you need is the strtotime() function. Changed date to gmdate, converting your servers time to GMT

For example if you need the time format like 10:00:00

gmdate("H:i:s", strtotime($gmt_offset . " hours"));

More info here:

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

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

like image 30
Chris Laarman Avatar answered Jan 19 '26 23:01

Chris Laarman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!