2013-10-25 50 views
1

我試圖在C#中實現CTime::GetTime()方法的行爲。在C#中實現相同的行爲CTime.GetTime()方法

在這裏有我的控制檯應用程序的代碼片段(用C++編寫/ CLI):

int main(array<System::String ^> ^args) 
{ 
int epochYear = 1970; 
int epochMonth = 1; 
int epochDay = 1; 

DateTime managedEpochDate = DateTime(epochYear, epochMonth, epochDay); 

int year = 2013; 
int month = 2; 
int day = 13; 
int hour = 9; 
int minutes = 49; 
int seconds = 46; 

// DateTime/CTime -> Numeric Time (__time64_t) 

DateTime managedDateTime = DateTime(year, month, day, hour, minutes, seconds); 
CTime nativeDateTime = CTime(year, month, day, hour, minutes, seconds); 

DWORD nativeTimeToSerialize = nativeDateTime.GetTime(); 
UInt32 managedTimeToSerialize = (managedDateTime - managedEpochDate) 
    .TotalSeconds; 
} 

在結束我有以下不同的值:

  • nativeTimeToSerialize = 1360745386
  • managedTimeToSerialize = 1360748986

任何人都可以幫助我理解這種差異的原因嗎?

+2

區別是3600秒或1小時。這與你的時區有什麼關係? – Jon

+2

CTime有聲明是否應考慮夏令時的功能 - 我的猜測是DateTime會自動執行此操作 - 因此小時的差異 – benjymous

+1

@benjymous實際上這是另一種方式 - 請參閱我的答案。 – BartoszKP

回答

1

的差異來自於一個事實,即CTime constructor您正在使用轉換時間UTC:

此構造進行適當轉換爲UTC。

鑑於DateTime構造器(和一個other)是時區在這種情況下不知道:

Kind屬性被初始化爲DateTimeKind.Unspecified

DateTimesubtraction operator也沒有考慮時區到:

執行減法時,Subtraction(DateTime, DateTime)方法不考慮兩個DateTimeKind屬性的值。

爲了得到期望的結果設定爲CTime構造函數的最後一個參數恰當,如:

CTime nativeDateTime = CTime(year, month, day, hour, minutes, seconds, 0); 

修改DateTime用途,而不是你需要有:

int epochYear = 1970; 
int epochMonth = 1; 
int epochDay = 1; 

DateTime managedEpochDateUtc 
    = new DateTime(epochYear, epochMonth, epochDay, 0, 0, 0, DateTimeKind.Utc); 

int year = 2013; 
int month = 2; 
int day = 13; 
int hour = 9; 
int minutes = 49; 
int seconds = 46; 

DateTime managedDateTimeLocal 
    = new DateTime(year, month, day, hour, minutes, seconds, DateTimeKind.Local); 

DateTime managedDateTimeUtc = managedDateTimeLocal.ToUniversalTime(); 

uint managedTimeToSerialize = (uint)(managedDateTimeUtc - managedEpochDateUtc) 
.TotalSeconds; 

或者,如通過Mgetz建議您可以使用DateTimeOffset而不是DateTime,這通常是推薦的,因爲DateTimedoesn't handle timezones very clearly

相關問題