2

I got some strange result for:

Console.WriteLine(new DateTime(1296346155).ToString());

Result is:

01.01.0001 0:02:09

But it is not right!

I parsed value 1296346155 from some file. It said that it is in UTC;

Please explain;)

Thank you for help!)))

Edward83
  • 6,664
  • 14
  • 74
  • 102
  • 1
    It may be a Unix time. Try this: http://stackoverflow.com/questions/249760/how-to-convert-unix-timestamp-to-datetime-and-vice-versa – Kobi Apr 12 '11 at 10:31
  • What was some file? I am guessing it was in WIN32 FileTime which uses January 1, 1601 (UTC) as its offset, not Jan 1, 0001. – Nic Strong Apr 12 '11 at 10:32

6 Answers6

5

DateTime expects "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." (from msdn)

This question shows how you can convert a unix timestamp to a DateTime.

Community
  • 1
  • 1
Twelve47
  • 3,924
  • 3
  • 22
  • 29
4

The constructor for DateTime that accept long type is expecting ticks value, not seconds or even milliseconds, and not from 1/1/1970 like in other languages.

So 1296346155 ticks is 129 seconds.

Shadow The GPT Wizard
  • 66,030
  • 26
  • 140
  • 208
3

If it's Unix time, then the following should yield the expected result;

DateTime baseTime = new DateTime(1970, 1, 1, 0, 0, 0);
Console.WriteLine(baseTime.AddSeconds(1296346155));

See Unix Time for more information.

Chris McAtackney
  • 5,192
  • 8
  • 45
  • 69
3

That constructor is not what you want as the time is not measured in ticks.

DateTime start = new DateTime(1970,1,1,0,0,0,0);
start = start.AddSeconds(1296346155).ToLocalTime();
Console.WriteLine(start);  
// You don't need to use ToString() in a Console.WriteLine call
trickdev
  • 627
  • 1
  • 7
  • 14
2

That is correct - what were you expecting it to be and why?

The constructor System.DateTime(Int64) takes the number of 100-nanosecond intervals (known as Ticks) since January 1st 0001 (in the Gregorian calendar).

Therefore, 1296346155 / 10000000 gives you the number of seconds, which is 129.6.

Therefore, this should display 2 minutes and 9 seconds since midnight on 1st January 0001.

Rob Levine
  • 40,328
  • 13
  • 85
  • 111
2

Ive found the following subject where there is a conversion between unix timestamp (the one you have) and .Net DateTime

How to convert a Unix timestamp to DateTime and vice versa?

Community
  • 1
  • 1
Yet Another Geek
  • 4,251
  • 1
  • 28
  • 40