John Davidson

Get user timezone string with Javascript / PHP?


I'm trying to get the user's timezone as a string on singup. example:

$timezone = "Asia/Tel_Aviv";

While researching the issue, I got how to Get timezone offset with Javascript, but I'm still unclear about how can I translate the timezone offset to a timezone string in php, as shown above?

Or, which other method cas I use in Javascript / PHP for getting the timezone string for each user?

I'm really not sure how to approach this.

My Answer:
To get the user's timezone as a string in PHP, you can use the following code:

$timezone = date_default_timezone_get();

This will give you the timezone string in the format "Continent/City" (e.g. "Asia/Tel_Aviv").

In JavaScript, you can get the user's timezone offset using the following code:

var offset = new Date().getTimezoneOffset();

You can then use this offset to determine the user's timezone string by comparing it with a list of known timezone offsets. Here is an example of how you can do this in JavaScript:

function getTimezone(offset) {
var timezones = {
"-720": "Pacific/Midway",
"-660": "Pacific/Pago_Pago",
"-600": "America/Adak",
"-540": "Pacific/Honolulu",
"-480": "America/Los_Angeles",
"-420": "America/Denver",
"-360": "America/Chicago",
"-300": "America/New_York",
"-240": "America/Caracas",
"-210": "America/Halifax",
"-180": "America/Argentina/Buenos_Aires",
"-120": "America/Noronha",
"-60": "Atlantic/Azores",
"0": "Europe/London",
"60": "Europe/Paris",
"120": "Europe/Istanbul",
"180": "Asia/Tel_Aviv",
"210": "Asia/Tehran",
"240": "Asia/Dubai",
"270": "Asia/Kabul",
"300": "Asia/Karachi",
"330": "Asia/Kolkata",
"345": "Asia/Kathmandu",
"360": "Asia/Dhaka",
"390": "Asia/Rangoon",
"420": "Asia/Bangkok",
"480": "Asia/Shanghai",
"525": "Australia/Eucla",
"540": "Asia/Tokyo",
"570": "Australia/Darwin",
"600": "Australia/Brisbane",
"630": "Australia/Adelaide",
"660": "Australia/Sydney",
"690": "Pacific/Norfolk",
"720": "Pacific/Auckland",
"765": "Pacific/Chatham",
"780": "Pacific/Tongatapu",
"840": "Pacific/Kiritimati"

return timezones[offset.toString()];

var offset = new Date().getTimezoneOffset();
var timezone = getTimezone(offset);

This code will output the user's timezone string based on their offset. You can then pass this timezone string to your PHP script for further processing.

Rate this post

4 of 5 based on 3751 votes


© 2024 - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us