0

I need to convert PHP timestamps according to the user's computer timezone.

Server's timezone is: UTC +1

To do this, first I use javascript.

<script>
var time_offset = new Date().getTimezoneOffset();
time_offset = Number(time_offset) * 60 + 3600;  //here I convert minutes to seconds and add 3600 seconds (1 hour) which is the difference between server's time and UTC.
var d = document.write(time_offset);
</script>

PHP

And here I got lost. Don't know how to use strtotime because time_offset can be negative and positive number:

$date_convert = '2022-10-27 12:25:46';
$offset = ob_get_clean();

// echo $offset; outputs negative value -3600 

$newdate = date("d/m/Y H:i", strtotime("$date_convert + $offset seconds"));

echo $newdate;

This produces:

01/01/1970 01:00

SanMiguel
  • 5
  • 2
  • `"$date_convert + $offset seconds"` is literally the string `"$date_convert + $offset seconds"` - `strtotime` doesn't know what date `"$date_convert + $offset seconds"` is – Jaromanda X Oct 27 '22 at 11:51
  • @JaromandaX it's PHP code, inside a double-quoted string it will substitute the values of `$date_convert` and `$offset` – Nick Oct 27 '22 at 11:54
  • @SamMiguel check your `$offset` value. See https://3v4l.org/XLcnq - only when it is a number, it works as expected. In all other cases you get the start off time (PHP time it is). So you probably do not have the right value in your variable. – Uwe Oct 27 '22 at 11:55
  • You can't pass values from JS to PHP by using `document.write`. You need to transfer them via some of form of request, typically a form submission or an ajax request – Nick Oct 27 '22 at 11:56
  • @Nick if I can not pass, how ´echo $offset´ outputs ´-3600´? – SanMiguel Oct 27 '22 at 12:22
  • @SanMiguel you must have more code than you are showing us... or are you sure that's the `echo` and not the `document.write`? Does `-3600` still show up if you delete the `document.write`? – Nick Oct 27 '22 at 12:25

0 Answers0