The below code snippet convert DateTime
to time_t
in c#. When in C++, i convert it back using localtime_s
I get tm_hour = 2
, why?
下面的代码片段将dateTime转换为c#中的time_t。在C ++中,我使用localtime_s将其转换回来我得到tm_hour = 2,为什么?
I convert: DateTimeUtils.Secs(DateTime.Parse("2015-05-01"))
public static Int64 Secs(DateTime dt)
{
var delta = dt - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
return Convert.ToInt64(delta.TotalSeconds);
}
time_t DropTimeFromDate(time_t time)
{
struct tm timeInfo;
localtime_s(&timeInfo, &time);
timeInfo.tm_hour = 0;
timeInfo.tm_min = 0;
timeInfo.tm_sec = 0;
return mktime(&timeInfo);
}
Should I somehow fix the c# conversion?
我应该以某种方式修复c#转换?
1 个解决方案
#1
I'm in the UK, presently UTC+1:00 (British Summer Time), running your code I get a tm_hour of 1 rather than 2 which I can only guess is due to us being in different timezones (UTC+1 isn't always UTC+1, timezones are just a headache in general)
我在英国,目前UTC + 1:00(英国夏令时间),运行你的代码我得到1而不是2的tm_hour我只能猜测是因为我们在不同的时区(UTC + 1 isn'总是UTC + 1,时区只是一个令人头疼的问题)
Either way the problem down to the C++ or C code you're using to convert back to time_t - the C# code is fine
无论哪种方式问题都归结为你用来转换回time_t的C ++或C代码 - C#代码很好
if you change localtime_s(&timeInfo, time) to gmtime_s(&timeInfo, time)
如果你将localtime_s(&timeInfo,time)更改为gmtime_s(&timeInfo,time)
you should have better luck, the latter ignores the current timezone and just treats the value as a raw UTC time which is best to work with if you can
你应该有更好的运气,后者忽略当前的时区,只是将值视为原始UTC时间,如果可以,最好使用
#1
I'm in the UK, presently UTC+1:00 (British Summer Time), running your code I get a tm_hour of 1 rather than 2 which I can only guess is due to us being in different timezones (UTC+1 isn't always UTC+1, timezones are just a headache in general)
我在英国,目前UTC + 1:00(英国夏令时间),运行你的代码我得到1而不是2的tm_hour我只能猜测是因为我们在不同的时区(UTC + 1 isn'总是UTC + 1,时区只是一个令人头疼的问题)
Either way the problem down to the C++ or C code you're using to convert back to time_t - the C# code is fine
无论哪种方式问题都归结为你用来转换回time_t的C ++或C代码 - C#代码很好
if you change localtime_s(&timeInfo, time) to gmtime_s(&timeInfo, time)
如果你将localtime_s(&timeInfo,time)更改为gmtime_s(&timeInfo,time)
you should have better luck, the latter ignores the current timezone and just treats the value as a raw UTC time which is best to work with if you can
你应该有更好的运气,后者忽略当前的时区,只是将值视为原始UTC时间,如果可以,最好使用