比较服务器上的客户端时间 [英] Comparing client time on the server

查看:106
本文介绍了比较服务器上的客户端时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在服务器上具有以下格式的字符串,则该字符串可以在任何时区:

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.

我尝试将客户端时间传递为​​自Unix时代以来的毫秒数:

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.

推荐答案

检出moment.js,它使愚蠢的日期解析变得很容易,并且具有用于处理时区转换的配套库(但通常不需要)。他们的文档中有一部分说明了UTC与本地的处理以及如何来回转换。

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())

这篇关于比较服务器上的客户端时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆