2012-12-21 12 views
0

我得到我的可執行文件的「LastWriteTime」,並將其與我設置的內部DateTime進行比較。如果LastWriteTime小於或等於內部DateTime,那麼我將清除數據庫中的兩個表。當用戶處於不同的時區時,如何停止日期/時間比較失敗?

此代碼適用於太平洋時區的我。但是,如果用戶在另一個時區(例如,比我早4個小時),則它不起作用,因爲「LastWriteTime」返回轉換爲其時區的時間。例如,我正在尋找「2012年12月12日上午8時38分12秒」的價值,如果他們比我早4小時,這個值會自動更改爲「12/12/2012 12:38:12 PM「在他們的系統上。

有人可以告訴我什麼,我應該修改我的代碼,以考慮到不同的時區,所以「LastWriteTime」和我的「build2023_EXE_Date」變量都返回相同的日期/時間,所以我比較兩個日期/無論我的最終用戶在哪個時區,時間值都不會失敗?

我使用.NET 3.5,而不是淨4.x的

//http://stackoverflow.com/questions/1600962/displaying-the-build-date 
string w_file = "MyEXE.exe"; 
string w_directory = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + 
         Path.DirectorySeparatorChar + "MyEXE"; 

DateTime currentExeTime = File.GetLastWriteTime(System.IO.Path.Combine(w_directory, w_file)); 


DateTime build2023_EXE_Date = new DateTime(2012, 12, 12, 8, 38, 12); //"12/12/2012 8:38:12 AM" 

//We need to truncate the millisecond time off of the EXE LastWriteTime 
//or else when we compare to our internal DateTime build2323_EXE_Date value, 
//it will not match 
//http://stackoverflow.com/questions/1004698/how-to-truncate-milliseconds-off-of-a-net-datetime 
currentExeTime = new DateTime(
    currentExeTime.Ticks - (currentExeTime.Ticks % TimeSpan.TicksPerSecond), 
      currentExeTime.Kind 
      ); 

if (currentExeTime <= build2023_EXE_Date) //If previous build matches or is before the Build 2023 date then clear these two tables. 
{ 
    //This will fail the comparision if the user is in a different time zone than me. 
    //Clear tables 
} 
+0

是不是'TimeZone'類嗎? ;) – bonCodigo

+0

另請參見http://msdn.microsoft.com/en-us/library/ms973825.aspx –

回答

1

使用DateTime ToUniversalTime()方法

+0

我的比較看起來像這樣?如果(c3.ToUniversalTime()<= build2023_EXE_Date.ToUniversalTime()) – fraXis

+0

在build2023_EXE_Date的情況下,沒有關於時區的信息,因此無論是設置還是隻比較build2023_EXE_Date和c3.ToUniversalTime()(如果您確定的話),build2023_EXE_Date是UTC – VladL

4

除非你有特別需要保持在日期本地時間或有關聯的時區,我建議你使用通用而不是時間。這使得處理日期變得更加容易,因爲它們都比較理性,並且它實際上可以更具性能(當您請求DateTime.Now,.NET調用DateTime.UtcNow,然後對本地時間執行相對昂貴的調整時)。

另一種選擇是使用DateTimeOffset,其中存儲有偏移的日期(不是一個時區 - 例如,DST會給你不同的偏移量),進行比較容易,因爲通用DateTime。不幸的是,GetLastWriteTime不使用DateTimeOffset,所以這可能不適合你。

+0

我沒有特別需要在任何特定時區保留日期。我只是想確定兩個日期,當我比較它們時,將它們翻譯成同一時區。 – fraXis

+0

會使用這項工作嗎? 「if(c3.ToUniversalTime()<= build2023_EXE_Date.ToUniversalTime())」如果不論用戶的時區是否滿足條件,是否會導致比較始終通過? – fraXis

+0

將數據庫中的日期保留爲通用時間,並讓客戶端在世界時間內發送它們的時間(只有客戶端知道它們在哪個時區,因此您無法在服務器上將其轉換) –