C# converting to and from Unix time - 1 day lost

Viewed 225

here is the code:

var date = DateTime.Now.Date;
var ms = (long)(date - DateTimeOffset.UnixEpoch).TotalMilliseconds;
var date1 = DateTimeOffset.FromUnixTimeMilliseconds(ms).DateTime.Date;

date is 24th and date1 is 23rd

why dont they match?

1 Answers

Use DateTimeOffset.FromUnixTimeMilliseconds(ms).LocalDateTime.

DateTime.Now has Kind = Local so it is eskewing your UTC offset.

You can see it with:

var kind = DateTime.Now.Date.Kind;

and then you can make a small test with the "kind":

var date = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Local);
var ms = (long)(date - DateTimeOffset.UnixEpoch).TotalMilliseconds;

How much ms is? Depending on winter/summer time and your location, it probably isn't 0.

So your ms includes your UTC offset. Now you have to:

var date1 = DateTimeOffset.FromUnixTimeMilliseconds(ms).LocalDateTime;

and let's hope you are still in the "original" utc offset (so not enough days have passed between the calculation of date and the calculation of date1 for you to switch between winter/summer time)

(if you did everything correctly, you don't really need the .Date after .LocalDateTime, because the date should already be 00:00:00)

Related