Conversion from milliseconds to DateTime format

后端 未结 3 938
面向向阳花
面向向阳花 2020-12-01 09:00

I got a string which is representend like this :

string startdatetime = \"13988110600000\"

What I want to do is to convert this string (wh

相关标签:
3条回答
  • 2020-12-01 09:34

    DateTime in .NET is initialized to 0001-01-01 00:00:00 and then you add your TimeSpan, which seems to be 45 Years.

    It is common for such (milli)-second time definitions to start at 1970-01-01 00:00:00, so maybe the following gives you the expected result:

    double ticks = double.Parse(startdatetime);
    TimeSpan time = TimeSpan.FromMilliseconds(ticks);
    DateTime startdate = new DateTime(1970, 1, 1) + time;
    

    or simply

    var date = (new DateTime(1970, 1, 1)).AddMilliseconds(double.Parse(startdatetime));
    
    0 讨论(0)
  • 2020-12-01 09:57

    The reason is that your value is based on milliseconds elapsed since 01/01/1900 or 01/01/1970 and DateTime in C# starts with 01/01/00001.

    I think it starts from 01/01/1970 because 1970 + 45 would be 2015 which I think it is the year you search.

    0 讨论(0)
  • 2020-12-01 09:59

    Since TimeSpan.Ticks property returns long, your new DateTime(time.Ticks) code call DateTime(long) constructor and from it's documentation;

    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.

    That's why it's wrong to say The result is almost good. The value of result is expected as implemented and documented.

    0 讨论(0)
提交回复
热议问题