C# DateTimeOffset bad hour. Difference TimeSpan to DateTime and DateTime to TimeSpan

61 Views Asked by At

u_date = 1688066111

DateTime p_date = DateTimeOffset.FromUnixTimeSeconds(u_date).DateTime;

Gives: 2023-06-29 19:15:11

long unixTime = ((DateTimeOffset)p_date).ToUnixTimeSeconds();

Gives: 1688058911 (2023-06-29 17:15:11)

How to fix that problem?

1

There are 1 best solutions below

1
Klaus Gütter On

Doing it step by step will reveal what happens:

  1. DateTimeOffset.FromUnixTimeSeconds(u_date) will give you 2023-06-29 19:15:11 +00:00, i.e. a date/time in UTC. Reference

  2. Getting the property DateTime will erase the time zone information (the resulting p_date has DateTimeKind.Unspecified). Reference

  3. ((DateTimeOffset)p_date) will interpret p_date as local time, i.e. in the current timezone which seems to be +02:00 in your case. Reference

You can fix this problem by avoiding the round-trip via DateTime, using only DateTimeOffset. Or - as Jon noted in his comment - by using the property UtcDateTime in step 2 (instead of DateTime) which will produce a a DateTime object with DateTimeKind.Utc (instead of DateTimeKind.Unspecified).