2

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.

Crimin4L
  • 610
  • 2
  • 8
  • 23
  • Does this answer your question? [How to convert between time zones in PHP using the DateTime class?](https://stackoverflow.com/questions/15625834/how-to-convert-between-time-zones-in-php-using-the-datetime-class) – Umer Abbas Apr 11 '20 at 04:15

2 Answers2

2

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>
thingEvery
  • 3,368
  • 1
  • 19
  • 25
  • Ok, updated. And if you want the date formatted differently, you can pass options to `toLocaleString()`. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString – thingEvery Apr 11 '20 at 04:48
  • 1
    >keeping it in PHP? I don't think so. PHP only knows what time the server has. You'll need to communicate with the user's browser to get their local offset. Hence the JS. – thingEvery Apr 11 '20 at 04:49
  • How can I just take the current time, and - it 4 hours in php lmaoo – Crimin4L Apr 11 '20 at 04:54
  • 1
    4 hours * 60 minutes * 60 seconds = 14400 seconds. Subtract 14400 from the timestamp. – thingEvery Apr 11 '20 at 04:58
0

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);
Crimin4L
  • 610
  • 2
  • 8
  • 23