12

I've created a DateTime value from an item being clicked in a listBox. It's in the format dd/MM/yyyy hh:mm:ss. I'm want to zoom in on a ten minute period with the clicked event in the middle. My current code is as follows (where zoom_time is the DateTime to zoom to on my chart;

chart1.ChartAreas[0].AxisX.Minimum = (Convert.ToDouble(zoom_time.AddMinutes(-5)));
chart1.ChartAreas[0].AxisX.Maximum = (Convert.ToDouble(zoom_time.AddMinutes(5)));

This breaks saying

"invalid cast from DateTime to double"

Any ideas guys?

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
tommy_20
  • 151
  • 1
  • 1
  • 6
  • 2
    because you are trying to cast a `DateTime` to a `double`, which you cannot do like that. What `double` value are you expecting to get from the `DateTime`? Give an example of input and output values that you want – musefan Jul 23 '13 at 08:23

4 Answers4

16

You can use DateTime.ToOADate(), if you mean ole automation date by double

BudBrot
  • 1,341
  • 2
  • 24
  • 44
3

Thanks for that!

For reference, the following works best;

            double start = (zoom_time.AddMinutes(-1)).ToOADate();
            double end = (zoom_time.AddMinutes(1)).ToOADate();

            chart1.ChartAreas[0].AxisX.Minimum = start;
            chart1.ChartAreas[0].AxisX.Maximum = end;
tommy_20
  • 151
  • 1
  • 1
  • 6
2

You have to use the ToOADate() methode like the following:

chart1.ChartAreas[0].AxisX.Minimum = zoom_time.AddMinutes(-5).ToOADate();
chart1.ChartAreas[0].AxisX.Maximum = zoom_time.AddMinutes(5).ToOADate();

Edit:

Should have refreshed my page before answering. :)

Rand Random
  • 7,300
  • 10
  • 40
  • 88
0

ToOADate() method that is mentioned in other answers here is not accurate!

It's better to use this:

double timestamp = DateTime.UtcNow.Ticks;

See this post where he loses precision when doing DateTime.Now.AddTicks(1000).ToOADate(), if the example there were changed to (double)DateTime.Now.AddTicks(1000).Ticks the precision is not lost.

BornToCode
  • 9,495
  • 9
  • 66
  • 83