1

我正在尝试在 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

谁能帮我理解这种差异的原因?

4

1 回答 1

1

不同之处在于您使用的CTime构造函数将时间转换为 UTC:

此构造函数对 UTC 进行适当的转换。

而在这种情况下,DateTime构造者(和另一个)是不知道时区的:

Kind属性被初始化为DateTimeKind.Unspecified

减法运算符也不DateTime考虑时区:

该方法在执行减法时Subtraction(DateTime, DateTime)不考虑这Kind两个值的属性值。DateTime

要获得所需的结果,请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,通常推荐使用,因为DateTime 它不能非常清楚地处理时区

于 2013-10-25T12:36:57.313 回答