问题
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