c# - UTC 时间服务器差异

标签 c# datetime

我有一个客户端和服务器端应用程序。客户端在英国服务器上,服务器在美国服务器上。

服务器上有一个验证,它检查消息何时从客户端发送并比较它以查看时间差异。

这就是我在客户端应用程序(英国)上获取时间跨度的方式:

DateTime epochStart = new DateTime(1970, 01, 01, 0, 0, 0, 0, DateTimeKind.Utc);
TimeSpan timeSpan = DateTime.UtcNow - epochStart;
// Convert to string before send it to server 
string requestTimeStamp = Convert.ToUInt64(timeSpan.TotalSeconds).ToString()

在服务器(美国)端我有:

DateTime epochStart = new DateTime(1970, 01, 01, 0, 0, 0, 0, DateTimeKind.Utc);
TimeSpan currentTs = DateTime.UtcNow - epochStart;

var serverTotalSeconds = Convert.ToUInt64(currentTs.TotalSeconds);
var requestTotalSeconds = Convert.ToUInt64(requestTimeStamp);

if ((serverTotalSeconds - requestTotalSeconds) > requestMaxAgeInSeconds)
{
     //....
}

当服务器和客户端在英国服务器上时一切正常,但在不同服务器上时就会出现问题。

我的问题是:

  1. 无论时区/时差如何,两台服务器上的 UTC 时间是否完全相同?
  2. 时间是否取自PC系统时间? (因此,如果系统中的时间设置错误,DateTime.UtcNow 会给我错误的时间吗?)

最佳答案

Is UTC time exact same on both servers no matter the time zone/time difference?

理论上,应该是。但是,根据客户端和服务器与之通信的 NTP 服务器,它们可能会有所不同。希望如果它们不同,那是一个非常的小差异。

Is the time taken from the PC system time? (so if the time is set to wrong one in the system the DateTime.UtcNow give me wrong time?)

是的,MSDN's DateTime.UtcNow documentation说如下:

Gets a DateTime object that is set to the current date and time on this computer, expressed as the Coordinated Universal Time (UTC).

关于c# - UTC 时间服务器差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30373026/

相关文章:

c# - LINQ Lambda 代码 groupby orderby 的效率

c# - 为什么 DataContractJsonSerializer 和 toSource 产生不同的结果?

mongodb - 如何使用原子操作增加 mongoDB 文档中的 Datetime 字段?吗啡也一样吗?

c++ - 如何读取 xsd :dateTime with msxml?

mysql - 如何使用 MySQL 合并连续的日期和时间行

c# - 如何在另一个窗口上设置窗口?

c# - 防止调用下一个事件处理程序

c# - 对于 : Razor with Javascript method inside tbody

android - 如何合并数据时间

python - strptime() argument 1 必须是str,不是Series 时间序列转换