How to Detect User'S Timezone

How to automatically detect user's timezone?

Use javascript solution

http://www.onlineaspect.com/2007/06/08/auto-detect-a-time-zone-with-javascript/

Demo should show your timezone in select box.

http://onlineaspect.com/examples/timezone/index.html (Dead link)

How to detect user's timezone?

To summarize Matt Johnson's answer in terms of code:

<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js">
</script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jstimezonedetect/1.0.4/jstz.min.js">
</script>
<script type="text/javascript">
$(document).ready(function(){
var tz = jstz.determine(); // Determines the time zone of the browser client
var timezone = tz.name(); //For e.g.:"Asia/Kolkata" for the Indian Time.
$.post("url-to-function-that-handles-time-zone", {tz: timezone}, function(data) {
//Preocess the timezone in the controller function and get
//the confirmation value here. On success, refresh the page.
});
});
</script>

Get timezone from users browser using moment(timezone).js

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

This returns the difference from the clients timezone from UTC time.
You can then play around with it as you like.

get client time zone from browser

Look at this repository pageloom it is helpful

download jstz.min.js and add a function to your html page

<script language="javascript">
function getTimezoneName() {
timezone = jstz.determine()
return timezone.name();
}
</script>

and call this function from your display tag

How to detect the timezone of a client?

Unfortunately this information is not passed in HTTP headers.

Usually you need cooperating JavaScript to fetch it for you.

Web is full of examples, here is one http://www.coderanch.com/t/486127/JSP/java/Query-timezone

Getting the client's time zone (and offset) in JavaScript

Using getTimezoneOffset()

You can get the time zone offset in minutes like this:

var offset = new Date().getTimezoneOffset();
console.log(offset);
// if offset equals -60 then the time zone offset is UTC+01

Detect timezone on client side

The best thing you can do is parse it on client side and send to the server the number of millis since EPOCH:

var millis = new Date(dateStr).getTime();

When you get the millis on server side, you can just create a Date object like this:

Date date = new Date(millis);

This will give you the correct date and time.

My advice: always use millis since EPOCH to avoid issues with timezones. Only convert to string when you need to show it to the user.



Related Topics



Leave a reply



Submit