简体   繁体   中英

How to Convert DateTime to Int, it is reading 'Invalid cast from 'DateTime' to 'Int32'?

I've got a for loop using a DateTime , I'm trying to add points to a chart by summing the data; however, when running the loop I get this error:

InvalidCastException was unhandled: Invalid cast from 'DateTime' to 'Int32'.

Here is the code in the for loop I am trying:

List<Series> dataSeries = chartDailyCost.Series.ToList();
for (DateTime i = Convert.ToDateTime("00:00"); 
              i <= (Convert.ToDateTime("23:45")); 
              i = i.AddMinutes(15))
{
    double sum = 0d;

    //for every series in the chart collection sum the yvalues at the specified 
    foreach (Series s in dataSeries)
    {
        //This is the line I am getting the error for
        sum += s.Points[Convert.ToInt32(i)].YValues[0];
    }
    DataPoint dp = new DataPoint();
    //Add a new yvalue to the datapoint for the summed series's

    //And I will get an error in this one as well
    dp.XValue = dataSeries[0].Points[Convert.ToInt32(i)].XValue;

    dp.YValues[0] = sum;
    sumSeries.Points.Add(dp);
}

You never actually need a DateTime , instead what you should do is loop over an int , like so:

const int intervalMinutes = 15;
const int numIntervals = 24 * (60/intervalMinutes);
for(int i = 0; i < numIntervals; ++i)
{
    double sum = 0d;

    //for every series in the chart collection sum the yvalues at the specified 
    foreach (Series s in dataSeries)
    {
        sum += s.Points[i].YValues[0];
    }
    DataPoint dp = new DataPoint();
    //Add a new yvalue to the datapoint for the summed series's

    //And I will get an error in this one as well
    dp.XValue = dataSeries[0].Points[i].XValue;

    dp.YValues[0] = sum;
    sumSeries.Points.Add(dp);
}

If you do need a DateTime inside of your loop, create it like so:

DateTime dateTime = new DateTime().AddMinutes(intervalMinutes * i);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM