Javascript - 如何获取特定国家/地区的当前时间和日期?例如:新西兰。

时间:2017-09-17 02:39:58

标签: javascript

当前网站托管在AWS ec2中。   因此,当我使用Date函数时,它返回aws本地时间和日期。   如何在这台服务器上获得当前的新西兰时间?

3 个答案:

答案 0 :(得分:3)

你有几种选择。

  1. 修改EC2 instances timezone并将其发送到客户端浏览器。
  2. 从网络浏览器客户端时区计算新西兰时间。
  3. 如果您遵循第一个选项,则可以使用HTTP请求获取服务器UTC时间。

    对于第二个选项,您需要在客户端浏览器中使用JavaScript计算新西兰的时间。

    // create Date object for current location
    var date = new Date();
    
    // convert to milliseconds, add local time zone offset and get UTC time in milliseconds
    var utcTime = date.getTime() + (date.getTimezoneOffset() * 60000);
    
    // time offset for New Zealand is +12
    var timeOffset = 12;
    
    // create new Date object for a different timezone using supplied its GMT offset.
    var NewZealandTime = new Date(utcTime + (3600000 * timeOffset));
    

    注意:这不会反映夏令时。

答案 1 :(得分:0)

你可以试试这个:

如果服务器是Linux服务器,则使用,

f(n)

答案 2 :(得分:0)

使用第三方api显示来自特定国家/地区的时间。您可以使用worldtimeapi.org/中的api。进行ajax调用,获取desired location的时间。您可以使用普通的javascript或使用任何ajax库来执行此操作。在这里,我包括两种方法:1)简单的javascript和2)使用axios

VANILLA JS

function getTime(url) {
    return new Promise((resolve, reject) => {
        const req = new XMLHttpRequest();
        req.open("GET", url);
        req.onload = () =>
            req.status === 200
                ? resolve(req.response)
                : reject(Error(req.statusText));
        req.onerror = (e) => reject(Error(`Network Error: ${e}`));
        req.send();
    });
}

现在使用此功能进行ajax调用

let url = "http://worldtimeapi.org/api/timezone/Pacific/Auckland";

getTime(url)
    .then((response) => {
        let dateObj = JSON.parse(response);
        let dateTime = dateObj.datetime;
        console.log(dateObj);
        console.log(dateTime);
    })
    .catch((err) => {
        console.log(err);
    });

AXIOS

axios({
    url:"http://worldtimeapi.org/api/timezone/Pacific/Auckland",
    method: "get",
})
    .then((response) => {
        let dateObj = response.data;
        let dateTime = dateObj.datetime;
        console.log(dateObj);
        console.log(dateTime);
    })
    .catch((err) => {
        console.log(err);
    });

希望有帮助。请记住,worldtimeapi.org/是第三方服务。如果他们选择终止服务,则您的代码将中断。编码愉快。

相关问题