Are Javascript date/time functions dependent on the client machine?

后端 未结 5 1559
孤独总比滥情好
孤独总比滥情好 2020-12-30 06:50

I was wondering if Javascript date/time functions will always return correct, universal dates/times or whether, Javascript being a client-side language, they are dependent

5条回答
  •  春和景丽
    2020-12-30 07:45

    Javascript's date() constructor will always get the time of local machine.

    The best way to get the universal time are

    1) get the time from your server by an ajax call. This method will always show your server time no matter where your user is.

    2) Get the time from an third party server. Use a third party server to get time from any time zone / country of the world. Here I'm explaining this method by using plain javascript and axios. The service I'm using is worldtimeapi.org/

    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/Etc/GMT";
    
    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/Etc/GMT",
        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.

提交回复
热议问题