How do you get the "last modified" date from a file in the correct time zone?

Viewed 886

So I am trying to get the Last Modified date of a file in PHP, I am using this:

$file = "my_file.txt";
$date = date("F j, Y H:i:s.", filemtime($file));

Now the problem is when I echo it, I do not get it in my timezone. It comes up in UTC time, but I am in UTC-4 timezone.

(e1:) How do I get it to show my timezone, or even (e2:) display it in the timezone for whoever is viewing the webpage?

Example 1: Lets say I update the file at 1pm (UTC-4). Anyone looking at the webpage will see it displayed as 1pm (UTC-4) regardless of where they are located.

Example 2: Say I update the file at 1pm (UTC-4), and someone from the timezone UTC is looking at my webpage; they will see the time 5pm (UTC), because that's the time I uploaded it in their timezone.

2 Answers

Get the server time from PHP and store it in an HTML element. (There are other ways to pass the data, but this one is pretty easy to understand.) Here, I just used the time() function to grab the current time. Your filemtime method should return a timestamp if you omit the formatting options.

Then, grab the timestamp from the <div> with JS. Since the JS want milliseconds, multiply it by 1000. Then use toLocalString() to offset it to the user's local time.

<div id="timeholder" data-time="<?php echo json_encode(time()); ?>"></div>
<script type="text/javascript">
    var date = new Date(document.getElementById('timeholder').dataset.time * 1000).toLocaleString();
    console.log(date);
</script>

For Example 1:

Thanks to @thingEvery for doing the math on how much I needed to subtract from the current timestamp.

$filetime = date("U", filemtime($pfile));
$hoursToSubtract = 4;
$timeToSubtract = ($hoursToSubtract * 60 * 60);
    
$mytime = $filetime - $timeToSubtract;

# I needed to print it in two different formats,
# that's why I split it up
$time1 = date("F j, Y", $mytime);
$time2 = date("g:i A [e-4]", $mytime);
Related