I got a string which is representend like this :
string startdatetime = "13988110600000"
What I want to do is to convert this string (which are milliseconds) to a DateTime variable. This is what I'm doing :
double ticks = double.Parse(startdatetime);
TimeSpan time = TimeSpan.FromMilliseconds(ticks);
DateTime startdate = new DateTime(time.Ticks);
The result is almost good : I've got a weird date but time is okay (30/04/0045 18:00:00).
Is there any reason to this?
Approach : First declare variable time and store the milliseconds of current date using new date() for current date and getTime() Method for return it in milliseconds since 1 January 1970. Convert time into date object and store it into new variable date. Convert the date object's contents into a string using date.
Use the Date() constructor to convert milliseconds to a date, e.g. const date = new Date(timestamp) . The Date() constructor takes an integer value that represents the number of milliseconds since January 1, 1970, 00:00:00 UTC and returns a Date object.
Usually we display time in in 12 hour format hh:mm:aa format (e.g. 12:30 PM) or 24 hour format HH:mm (e.g. 13:30), however sometimes we also want to show the milliseconds in the time. To show the milliseconds in the time we include “SSS” in the pattern which displays the Milliseconds.
If you need milliseconds, you need to add a further multiplication / division by 1000. For example, converting from epoch time (milliseconds) to a date would be "=((((A1/1000)/60)/60)/24)+DATE(1970,1,1)".
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));
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With