0

I just tried to convert a date stored as a long value into a DateTime but it gives me the date {2/01/0001 7:35:22 PM} whereas it should be {23/09/2019 4:30:23} (GMT +10)

Here is the long value 1569220232761 created on initialising the object. Here is the code that returns 2/01/0001

SeshStart = new DateTime(CurrentSession.startDate, DateTimeKind.Local);

With CurrentSession.startDate equal 1569220232761.

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Nicolas Guerin
  • 356
  • 2
  • 18

2 Answers2

4

What you have is a Unix Time, not the number of Ticks (which would be orders of magnitudes larger)

i.e 637,048,098,230,000,000 apposed to 1,569,220,232,761

Unix time

Unix time (also known as Epoch time, POSIX time, seconds since the Epoch, or UNIX Epoch time) is a system for describing a point in time. It is the number of seconds that have elapsed since the Unix epoch, that is the time 00:00:00 UTC on 1 January 1970,

DateTime(Int64)

Initializes a new instance of the DateTime structure to a specified number of ticks.

Try something like this

public static DateTime UnixTimeToDateTime(long unixtime)
{
   var dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
   return dtDateTime.AddMilliseconds(unixtime).ToLocalTime();
}
TheGeneral
  • 79,002
  • 9
  • 103
  • 141
  • 1
    Dope thanks ! Added it to my helpers thanks a lot ```SeshStart = DataHelpers.DateTimeHelper.DateFromUnixTime(CurrentSession.startDate); ``` – Nicolas Guerin Sep 23 '19 at 06:45
2

Because you are calling DateTime(Int64, DateTimeKind) overload and as stated;

Parameters

ticks

Int64

A date and time expressed in the number of 100-nanosecond intervals that have elapsed since January 1, 0001 at 00:00:00.000 in the Gregorian calendar.

As a Ticks, 1569220232761 is equal to Monday, 23 September 2019 06:30:32.761 GTM and you can calculate your value exactly how explained on How can I convert a Unix timestamp to DateTime and vice versa? question.

Also be aware, with .NET 4.6 version, two method introduced as DateTimeOffset.FromUnixTimeSeconds(Int64) and DateTimeOffset.ToUnixTimeSeconds.

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
  • 1
    Up vote, this is a really good answer, I always forget about those 2 methods, I'll have to update my libs – TheGeneral Sep 23 '19 at 21:54