C# : Converting a timestamp to a DateTime, then back to a timestamp gives different values

Advertisements

I have a huge text file of entries, all of which have a timestamp.
These entries are read and the timestamp on each entry is converted to a DateTime.
The problem is that the timestamps are different if the DateTime objects are converted back, this is causing a problem with false duplicates and generally a colossal mess in my dataset.

Here is sample input:

4144.6,4145.1,4142.6,4143.6,1654034400
4143.5,4143.9,4141.1,4141.6,1654034700
4141.6,4143,4141.1,4142.4,1654035000
4142.6,4143,4141.1,4141.9,1654035300

Here is how the Timestamps are converted to DateTimes, and converted back immediately for testing purposes:(SplitLine is the line from the txt file, split apart into its individual entries)

DateTime stamp = DateTimeOffset.FromUnixTimeSeconds(long.Parse(SplitLine[4])).DateTime;
Console.WriteLine((SplitLine[4]+ " becomes " +((DateTimeOffset)stamp).ToUnixTimeSeconds()));

The output from the above code block is as follows:

1654034400 becomes 1654027200
1654034700 becomes 1654027500
1654035000 becomes 1654027800
1654035300 becomes 1654028100

The 1st line of this output tells me Tue May 31 2022 22:00:00 GMT+0000 becomes Tue May 31 2022 20:00:00 GMT+0000.

I do not understand this, since the timezone does not change at any point during the data load. It is not particularly important about the timezone, but the data needs to be consistent. Does anybody have any idea whats going on here? Any help greatly appreciated.

>Solution :

Short Answer

Use .UtcDateTime on the first line, not .DateTime.

Explanation

The DateTimeOffset.DateTime property has its Kind set to DateTimeKind.Unspecified, whereas DateTimeoffset.UtcDateTime will have DateTimeKind.Utc.

When you cast the DateTime to a DateTimeOffset with ((DateTimeOffset)stamp), that’s taking stamp.Kind into consideration. In doing so, if the kind is DateTimeKind.Unspecified, it will treat it as if it were local time. You can read more about this in the remarks section of the docs (below the sample code).

By using the UtcDateTime, your stamp.Kind will be DateTimeKind.Utc, and the cast will not apply the local time zone.

Leave a ReplyCancel reply