C# strange with DateTime
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开发者_如何学JAVA!
I parsed value 1296346155 from some file. It said that it is in UTC;
Please explain;)
Thank you for help!)))
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.
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.
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.
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
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?
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.
精彩评论