简体   繁体   中英

DateTime to time_t produces Hour: 2 on c++ side

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?

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?

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)

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

if you change localtime_s(&timeInfo, time) to 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM