I am working with Visual Studio 2010, MVC 3 and C#. I am creating some highcharts and need to have the x-axis be a date. I am pulling the dates from a database and adding them to and array that will then be passed to highcharts. I think highcharts requires the dates to be in millisecond format. Ho do I go about converting a DateTime of '12/20/2011 5:10:13 PM" for example to milliseconds?
-
Do you mean you need the `DateTime` value in Unix epoch format, as described [here](http://stackoverflow.com/questions/8700823/datetime-format-from-unix-epoch)? – Oded Mar 15 '12 at 16:46
-
4What do you mean by millisecond format? The number of milliseconds elapsed since the Unix epoch? Since 01/01/0001? – Kendall Frey Mar 15 '12 at 16:47
4 Answers
Once you figure out what you want to calculate milliseconds from, you can just take one DateTime object from another to get a TimeSpan object. From TimeSpan you can get TotalMilliseconds.
In other words, if start and end are DateTime objects, you can do this:
double milliseconds = (end - start).TotalMilliseconds;

- 44,552
- 18
- 99
- 171
-
I am not quite sure yet what I want to calculate milliseconds from. I just know that I can't pass a DateTime object to HighCharts. For data it only accepts Number values. I tested your solution out and it appears to work. I received a couple of acceptable answers. However, I think yours is the cleanest and easiest to use. Thanks for the help. – Linger Mar 15 '12 at 21:03
You can use the DateTime.Ticks property and convert the value to milliseconds.
The value of this property represents the number of 100-nanosecond intervals that have elapsed since 12:00:00 midnight, January 1, 0001, which represents DateTime.MinValue. It does not include the number of ticks that are attributable to leap seconds.
A single tick represents one hundred nanoseconds or one ten-millionth of a second. There are 10,000 ticks in a millisecond.

- 1
- 1

- 17,024
- 9
- 81
- 111
The .Ticks
in C# DateTime
gives you the value of any time in ticks. You can thereafter convert to milliseconds as shown below:
long dateticks = DateTime.Now.Ticks;
long datemilliseconds = dateticks / TimeSpan.TicksPerMillisecond;

- 2,240
- 1
- 19
- 20
-
Please test your code before you post. I fixed simple errors in your code. – Enigmativity Apr 22 '18 at 01:51
-
The correct way to do this would be `long datemilliseconds = dateticks / TimeSpan.TicksPerMillisecond;`. Don't use magic numbers. – Enigmativity Apr 22 '18 at 01:53
DateTime[] dates = ;
var minDate = dates.Min();
var msDates = dates.Select(date => (date - minDate).TotalMilliseconds).ToArray();

- 16,581
- 4
- 54
- 61
-
This was my assumption as well that a minimum reference date is required. – ChaosPandion Mar 15 '12 at 16:48