How to get the client’s time zone

I want to save the timezone of client (visitor) that my web portal will use. could you show me a way to find out the timezone for client machine using JAVAScript code timezone for client machine using JAVAScript ...

 I need the GMT offset hours like `(GMT +5:30)`. 
+4
source share
4 answers

which works for me ...

 <script type="text/javascript" language="javascript" > function fnLoad() { var objLocalZone = new Date(); var strLocalZone=''+objLocalZone; var mySplitResult = strLocalZone.split(" "); var newLocalZone = mySplitResult[5].slice(0,mySplitResult[5].length-2) +':'+mySplitResult[5].slice(mySplitResult[5].length-2,mySplitResult[5].length); document.getElementById("hdnTimeZone").value = newLocalZone; //alert('Length : '+newLocalZone); } </script> 

hidden input

 <input type="hidden" id="hdnTimeZone" name="hdnTimeZone"/> 

I do not know that this is the right way to get the time zone of the client (visitor). but it works great for me. If anyone has the best solution, let me know. thanks...

+1
source

This might be the best approach for locating local time / client offset

 function pad(number, length){ var str = "" + number; while (str.length < length) { str = '0'+str; } return str; } var offset = new Date().getTimezoneOffset(); offset = ((offset<0? '+':'-')+ pad(parseInt(Math.abs(offset/60)), 2)+":"+pad(Math.abs(offset%60), 2)); alert(offset); 

The output will be = +05: 30

+8
source
 var OffSetMinute = new Date().getTimezoneOffset(); 

OffSetMinute var will give the difference in minutes between UTC and local time. The offset is positive if the local time zone is outside UTC and negative if it is ahead.

As @Guillaume said in a comment, the specified method is canceled, so you can use the following

  private static final Calendar cal = new Calendar(); private static final int LOCALTIMEZONEOFFSET = (cal.get(Calendar.ZONE_OFFSET) + cal.get(Calendar.DST_OFFSET)) / (60*1000); 

Calendar.ZONE_OFFSET gives the standard offset (in msecs) from UTC . This does not change with DST. (Daylight)

Calendar.DST_OFFSET gives the current DST offset (in msecs) - if any. For example, in the summer in a country using DST, this field most likely has a value +1 hour (1000*60*60 msecs) .

so just ADD int LOCALTIMEZONEOFFSET Value (if positive) or substarct value (if your value is negative) in your UTC Time , and this will give you time for the client computer.

+3
source
 function getTimezone() { var u = new Date().toString().match(/([-\+][0-9]+)\s/)[1]; return u.substring(0, 3) + ':' + u.substring(3, u.length); } 
+2
source

Source: https://habr.com/ru/post/1490216/


All Articles