我试图在一台服务器上用 JavaScript 创建一个 UTC 日期,并通过 URL 查询字符串将其传递到另一台服务器,C# 可以在其中获取该查询字符串,将其识别为日期并将其与新的 C# UTC 日期进行比较 -事实证明我比这更棘手(除非我只是其中之一)。我没有在 stackoverflow 上看到任何其他问题(在输入问题时显示的“相似标题”或“相似问题”列表中)。
为了在 JavaScript 中创建数据,我使用以下基于 this w3schools article 的代码:
var currentDate = new Date();
var day = currentDate.getUTCDate();
var month = currentDate.getUTCMonth();
var year = currentDate.getUTCFullYear();
var hours = currentDate.getUTCHours();
var minutes = currentDate.getUTCMinutes();
var seconds = currentDate.getUTCSeconds();
var milliseconds = currentDate.getUTCMilliseconds();
var expiry = Date.UTC(month,day,year,hours,minutes,seconds,milliseconds);
结果看起来像这样 1311871476074
那么,在 C# 中,我如何从查询字符串中获取此值并
- 将其转换为正确的日期,并
- 将其与基于 C# 的 UTC DateTime 变量进行比较?
我的逻辑/代码中的任何提示、更正或文章链接都将不胜感激。
凯文
更新
下面的两个答案都帮助我解决了我的问题:Luke 在 C# 方面提供了帮助,Ray 在 JavaScript 方面提供了帮助——不幸的是,我不能将它们都标记为答案,但我希望我可以!
最佳答案
JavaScript UTC
method返回自 1970 年 1 月 1 日 00:00:00 UTC 以来的毫秒数。要将这些毫秒转换回 C# 中的 DateTime
,您只需将它们添加到原始“纪元”:
string rawMilliseconds = Request.QueryString["expiry"];
if (string.IsNullOrWhiteSpace(rawMilliseconds))
throw new InvalidOperationException("Expiry is null or empty!");
long milliseconds;
if (!long.TryParse(rawMilliseconds, out milliseconds))
throw new InvalidOperationException("Unable to parse expiry!");
DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
DateTime expiry = epoch.AddMilliseconds(milliseconds);
关于c# - 如何比较在 Javascript 中创建的 UTC 日期与在 C# 中创建的 UTC 日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6862620/