We need to convert **datetime to int in c#** for example when we want to add new series of the data in chart control to previously added series of data where x axis was given in datetime format. If in this additional data series we have X axes values as integers, chart control will automatically convert this X axses data into datetime format. Problem is that we indexed X axes data in order to appearance (1,2,…), chart will convert this data into date 1900/1/1, 1900/1/2 and so forth. In order to allay new data series with previous datetime we can use simple linear conversion:

Y_{MIN_DATE} = *a*_{XMIN_VALUE} + *b*

and

Y_{MAX_VALUE} = *a*_{XMAX_VALUE} + *b*

and calculate a and b coefficients.

Then we can calculate corresponding datetime values to given X axis data values:

Y = *a*X + *b*.

But we need to convert XMIN_VALUE (that is integer) to corresponding Y_{MIN_DATE} that is datetime with the following** datetime to int c#** conversion code:

*int int_Smallest_X = (int)(dtSmallest. Date – new DateTime(1900, 1, 1)).TotalDays + 2;*

In here dtSmallest is of datetime format.

Reverse conversion goes with following code:

*dtSmallest = DateTime(1900, 1, 1). AddDays(int_Smallest_X – 2);*

Or we can do it in following way:

**TimeSpan** span = dtFirst.Subtract(dtSecond);

int int_days = (int)**span.TotalDays**;

**External links:**

Convert Datetime to int c# in Stackoverflow

## Leave a Reply