我正在尝试在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;
}
最后,我有以下不同的值:
任何人都可以帮我理解这种差异的原因吗?
答案 0 :(得分:1)
区别在于您使用的CTime
constructor将时间转换为UTC:
此构造函数适当转换为UTC。
在这种情况下,DateTime
构造函数(和other构造函数)是时区未知的:
Kind
属性初始化为DateTimeKind.Unspecified
。
DateTime
的{{3}}也不考虑时区:
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;
或者,根据subtraction operator的建议,您可以使用Mgetz代替DateTime
,这通常是推荐的DateTime
DateTimeOffset
。