Use Cases of Getting the Browser's Timezone
Getting the user timezone can help your application in showing date and time relative to the user's browser. This means that a user in New York will see time relative to America/New_York timezone, while a user in India will see time according to the Asia/Kolkata timezone.
Another use-case can be using the user's timezone to create an event on his behalf with Calendar APIs such as that of Google and Outlook. The user can choose a time from the frontend, and in the backend the application creates an event at that time, using the browser's timezone. It should be noted that all Calendar APIs need a timezone to create an event.
Detecting the User Timezone Name
Detecting the user timezoone is a two-step process:
- Convert the timezone offset to a valid TZ Database timezone name such as America/New_York, Asia/Kolkata.
1) Getting the Browser Timezone Offset
It should be noted that getTimezoneOffset returns an offset which is positive if the local timezone is behind UTC and negative if it is ahead. So we must add an opposite sign (+ or -) to the offset.
var timezone_offset_minutes = new Date().getTimezoneOffset(); timezone_offset_minutes = timezone_offset_minutes == 0 ? 0 : -timezone_offset_minutes; // Timezone difference in minutes such as 330 or -360 or 0 console.log(timezone_offset_minutes);
2) In PHP, Convert Timezone Offset in Minutes to a Timezone Name
You can get the timezone name from timezone offset in minutes through the timezone_name_from_abbr function.
Now when you get the timezone name, you can get date and time relative to the user's timezone :
Click on the button below to see the name of your current timezone :