Get time of specific timezone [duplicate]

2019-01-03 02:09发布

This question already has an answer here:

I am using a JavaScript Date class & trying to get the current date using getDate() method. But obviously it is loading system date & time. I am running the code from India but I want to get the date & time of UK using the same method. How can I do that ?

9条回答
Luminary・发光体
2楼-- · 2019-01-03 02:59

Date.getTimezoneOffset()

The getTimezoneOffset() method returns the time difference between Greenwich Mean Time (GMT) and local time, in minutes.

For example, If your time zone is GMT+2, -120 will be returned.

Note: This method is always used in conjunction with a Date object.

var d = new Date()
var gmtHours = -d.getTimezoneOffset()/60;
document.write("The local time zone is: GMT " + gmtHours);
//output:The local time zone is: GMT 11
查看更多
Evening l夕情丶
3楼-- · 2019-01-03 03:00

The .getTimezoneOffset() method should work. This will get the time between your time zone and GMT. You can then calculate to whatever you want.

查看更多
▲ chillily
4楼-- · 2019-01-03 03:05

If you know the UTC offset then you can pass it and get the time using the following function:

function calcTime(city, offset) {
    // create Date object for current location
    var d = new Date();

    // convert to msec
    // subtract local time zone offset
    // get UTC time in msec
    var utc = d.getTime() + (d.getTimezoneOffset() * 60000);

    // create new Date object for different city
    // using supplied offset
    var nd = new Date(utc + (3600000*offset));

    // return time as a string
    return "The local time for city"+ city +" is "+ nd.toLocaleString();
}

alert(calcTime('Bombay', '+5.5'));

Taken from: Convert Local Time to Another

查看更多
登录 后发表回答