gpt4 book ai didi

c# - 在 C# 中实现与 CTime.GetTime() 方法相同的行为

转载 作者:太空宇宙 更新时间:2023-11-04 11:46:42 25 4
gpt4 key购买 nike

我正在尝试在 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
  • ma​​nagedTimeToSerialize = 1360748986

任何人都可以帮助我理解这种差异的原因吗?

最佳答案

不同之处在于 CTime constructor您正在使用将时间转换为 UTC:

This constructor makes the appropriate conversion to UTC.

DateTime在这种情况下,构造函数(和 other 一个)不知道时区:

The Kind property is initialized to DateTimeKind.Unspecified.

subtraction operator DateTime 也不考虑时区:

The Subtraction(DateTime, DateTime) method does not consider the value of the Kind property of the two DateTime values when performing the subtraction.

要获得所需的结果,请适本地设置 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 doesn't handle timezones very clearly .

关于c# - 在 C# 中实现与 CTime.GetTime() 方法相同的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19589831/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com