Javascript - How to Get Current time and Date of specific country? eg: New Zealand.

Viewed 7129

Current website is hosted in AWS ec2. So when I am using Date function, it returns aws local time and date. How to get current New Zealand time in this server?

3 Answers

Use a third party api to show time from a specific country. You can use api from worldtimeapi.org/. Make an ajax call, get the time of your desired location. You can use plain javascript or use any ajax library to do that. Here I'm including two methods: 1) plain javascript and 2) using 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();
    });
}

Now Use this function to make the ajax call

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);
    });

Hope that helps. Bear one thing in mind though, worldtimeapi.org/ is a third party service. If they choose to terminate their service, your code will break. Happy coding.

Related