Getting the client's timezone offset in JavaSc

2018-12-31 01:40发布

How can I gather the visitor's time zone information? I need the Timezone, as well as the GMT offset hours.

23条回答
梦寄多情
2楼-- · 2018-12-31 01:52

On the new Date() you can get the offset, to get the timezone name you may do:

new Date().toString().replace(/(.*\((.*)\).*)/, '$2');

you get the value between () in the end of the date, that is the name of the timezone.

查看更多
泪湿衣
3楼-- · 2018-12-31 01:53

I realize this answer is a bit off topic but I imagine many of us looking for an answer also wanted to format the time zone for display and perhaps get the zone abbreviation too. So here it goes...

If you want the client timezone nicely formatted you can rely on the JavaScript Date.toString method and do:

var split = new Date().toString().split(" ");
var timeZoneFormatted = split[split.length - 2] + " " + split[split.length - 1];

This will give you "GMT-0400 (EST)" for example, including the timezone minutes when applicable.

Alternatively, with regex you can extract any desired part:

For "GMT-0400 (EDT)" :

new Date().toString().match(/([A-Z]+[\+-][0-9]+.*)/)[1]

For "GMT-0400" :

new Date().toString().match(/([A-Z]+[\+-][0-9]+)/)[1]

For just "EDT" :

new Date().toString().match(/\(([A-Za-z\s].*)\)/)[1]

For just "-0400":

new Date().toString().match(/([-\+][0-9]+)\s/)[1]

Date.toString reference: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/toString

查看更多
高级女魔头
4楼-- · 2018-12-31 01:53

you can simply try this. it will return you current machine time

var _d = new Date(), t = 0, d = new Date(t*1000 + _d.getTime())

查看更多
冷夜・残月
5楼-- · 2018-12-31 01:54

If all you need is the "MST" or the "EST" time zone abbreviation:

function getTimeZone(){
    var now = new Date().toString();
    var timeZone = now.replace(/.*[(](.*)[)].*/,'$1');//extracts the content between parenthesis
    return timeZone;
}
查看更多
浪荡孟婆
6楼-- · 2018-12-31 01:54

Timezone in hours-

var offset = new Date().getTimezoneOffset();
if(offset<0)
    console.log( "Your timezone is- GMT+" + (offset/-60));
else
    console.log( "Your timezone is- GMT-" + offset/60);

If you want to be precise as you mentioned in comment, then you should try like this-

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

if(offset<0)
{
    var extraZero = "";
    if(-offset%60<10)
      extraZero="0";

    console.log( "Your timezone is- GMT+" + Math.ceil(offset/-60)+":"+extraZero+(-offset%60));
}
else
{
    var extraZero = "";
    if(offset%60<10)
      extraZero="0";

    console.log( "Your timezone is- GMT-" + Math.floor(offset/60)+":"+extraZero+(offset%60));
}

查看更多
孤独寂梦人
7楼-- · 2018-12-31 01:54

This will do the job.


var time = new Date(),
timestamp = Date(1000 + time.getTime());
console.log(timestamp);

Thu May 25 2017 21:35:14 GMT+0300 (IDT)

undefined

查看更多
登录 后发表回答