0

So i have tried some other solutions from here but none have worked. My current method is trying to use the TimeSpan method:

unixtime is an int, contains '1502557200'

var test_date = TimeSpan.FromSeconds(unixtime);

test_date became '{17390.17:00:00}'

What am I doing wrong? I was trying to avoid creating a method to handle the conversion, and just trying to do it inline,

Thankyou

Metzer
  • 211
  • 1
  • 6
  • 20

1 Answers1

4

The Unix Epoch is 1970-01-01 00:00 UTC1.

But the .NET zero time is slightly earlier. So you covert as an offset from the Unix Epoch:

var dt = (new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).AddSeconds(unixTime);

This is simpler in .NET Core and .NET 5.0 (and later) with the addition of the field DateTime.UnixEpoch:

var dt = DateIMe.UnixEpock.AddSeconds(unixTime);

There is also DateTimeOffset.UnixEpoch.

1 Was defined later than this, so "what UTC would have been if it had existed".

Richard
  • 106,783
  • 21
  • 203
  • 265