[英]How can I compare a UTC date created in Javascript to a UTC date in C#?
我正在嘗試在一台服務器上用JavaScript創建一個UTC日期,並通過URL查詢字符串將其傳遞給另一台服務器,其中C#可以接受該查詢字符串,將其識別為日期並將其與新的C#UTC日期進行比較 - 並且它正在證明我覺得比較棘手(除非我只有其中一天)。 我沒有在stackoverflow上看到任何其他問題(在鍵入問題時顯示的“類似標題”或“類似問題”列表中)。
要在JavaScript中創建數據,我將使用以下內容,基於這篇w3schools文章 :
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#中如何從查詢字符串中獲取此值
我的邏輯/代碼中的任何提示,更正或文章鏈接都將非常感激。
凱文
UPDATE
下面的答案都幫助我解決了我的問題:Luke幫助了C#方面的事情,Ray幫助了JavaScript - 不幸的是我無法將它們都標記為答案,但我希望我能做到!
JavaScript UTC
方法返回自1970年1月1日00:00:00 UTC以來的毫秒數。要將這些毫秒轉換回C#中的DateTime
,您只需將它們添加到原始的“epoch”:
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);
日期時間對象表示時間瞬間,通常在內部表示為自紀元以來的毫秒數。 在JavaScript中,為當前時間獲取此值,它更容易使用
new Date().getTime()
現在您只需要一個數字(或包含數字的字符串),您可以將其傳遞給C#應用程序並從中構造DateTime對象。
為此,我可以將您引用到C#convert UTC int到DateTime對象 (Jon Skeet有答案。):)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.