Home > Article > Web Front-end > How to Efficiently Determine a User\'s Time Zone in PHP and JavaScript?
Problem:
How do you efficiently determine a user's time zone in both PHP and JavaScript?
Solution:
In PHP, you can retrieve the time zone offset as a session variable:
<code class="php"><?php session_start(); $timezone = $_SESSION['time']; ?></code>
To do this via JavaScript, include jQuery and incorporate the following code in the
section:<code class="javascript"><script type="text/javascript"> $(document).ready(function() { if ("<?php echo $timezone; ?>".length == 0){ var visitortime = new Date(); var visitortimezone = "GMT " + -visitortime.getTimezoneOffset()/60; $.ajax({ type: "GET", url: "http://example.com/timezone.php", data: 'time='+ visitortimezone, success: function(){ location.reload(); } }); } }); </script></code>
Finally, create a timezone.php file with:
<code class="php"><?php session_start(); $_SESSION['time'] = $_GET['time']; ?></code>
This combination of PHP and JavaScript will retrieve the user's time zone and store it as the $timezone variable in PHP.
The above is the detailed content of How to Efficiently Determine a User\'s Time Zone in PHP and JavaScript?. For more information, please follow other related articles on the PHP Chinese website!