Comparing client time on the server

跟風遠走 提交于 2020-06-17 03:15:50

问题


If I have a string of the following format on the server, which could be in any timezone:

var timeString = 2014-05-24T14:00:00.000Z

What is the best way to to compare the hour represented by the string with the hour that a client may pass in as part of a GET request (Node.js)?

I need help because the date on the server and the date received from the client may be in Daylight Savings time, or in different timezones.

I tried passing in the client time as the number of milliseconds since Unix epoch:

var clientTime = new Date(parseInt(req.query.localTime));
var serverTime = new Date(timeString);
if (serverTime.getUTCHours() == clientTime.getUTCHours()) {
    // the hours match
}

But it doesn't seem to work out.


回答1:


Have you checked out moment.js, it makes date parsing stupid easy and has a companion library for dealing with timezone conversion (but not usually needed). There is a section in their documentation that explains dealing with UTC vs local and how to convert back and forth.

http://momentjs.com/docs/#/parsing/utc/

var moment = require('moment')
var timeString = '2014-11-14T00:06:34.000Z'
var epochTime = 1415923594000

var serverTime = moment(timeString).utc()
var clientTime = moment(epochTime).utc()


console.log(serverTime.hour());
console.log(clientTime.hour())



回答2:


Trace this, you will get your answer:

app.get('/', (req, res) => {
    res.send('<script>var r=new Date().valueOf() + ( ' + (new Date().getTimezoneOffset()) +
        ' - (new Date().getTimezoneOffset()) ) * -60000;' +
        'setInterval(()=>{document.body.innerHTML = (new Date(r+=1000)).toLocaleString("en",{weekday:"long", month:"long", day:"numeric", year:"numeric", hour:"numeric", minute:"numeric", second:"numeric", hour12:false})},1000);' +
        '</script>');
});


来源:https://stackoverflow.com/questions/26919667/comparing-client-time-on-the-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!