How to get Client side time zone

匿名 (未验证) 提交于 2019-12-03 03:10:03

问题:

i want to store timezone of client (visitor) which going to use my web portal. would you please show me way to find out timezone for client machine using JAVAScript code...

I need the GMT offset hours like `(GMT +5:30)`.

回答1:

This could be a better approach to find client local time/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 would be like = +05:30



回答2:

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 timezone is behind UTC and negative if it is ahead.

As said in comment by @Guillaume the above method is deprected so you can use 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 you the standard offset (in msecs) from UTC. This doesn't change with DST. (Day Light Saving)

Calendar.DST_OFFSET gives you the current DST offset (in msecs) - if any. For example during summer in a country that uses DST this field is likely to have the value +1 hour (1000*60*60 msecs).

so just ADD int LOCALTIMEZONEOFFSET Value(if positive) or substarct the value (if your value is negative) into your UTC Time and that Will Give you client machine's time.



回答3:

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


回答4:

code that 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 don't know this is proper way to get client(visitor)'s timezone. but it works fine for me.If anybody have optimum solution this let me know. thanks...



转载请标明出处:How to get Client side time zone
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!