, , , , ,

How to use DateDiff Function in C#

How to use DateDiff Function in C#.

As earlier in ASP and VB6 we have too may conversion and date time functions.

After working for so many years, we all had become habitual of working with the same.

We have almost all the functions available in c#. But, sometimes lost control on some functions.

Like for datediff WE have to write so much code in C#. At this moment we just remember functions of VB.

Now, say thanks to Microsoft… What we can use is:-

Add a reference of Microsoft.VisualBasic and access the DateDiff function like following ex.

long nYears = Microsoft.VisualBasic.DateAndTime.DateDiff(Microsoft.VisualBasic.DateInterval.Year,
dt, dtNow,

By using the reference of visual basic you can use any function of Visual Basic or vice-versa.


Shakti Singh Dulawat said...

Yes datediff is nice function, but one more function you can use.

private double DateDiff(string howtocompare, System.DateTime startDate, System.DateTime endDate)
double diff=0;
System.TimeSpan TS = new System.TimeSpan(endDate.Ticks-startDate.Ticks);

switch (howtocompare.ToLower())
case "year":
diff = Convert.ToDouble(TS.TotalDays/365);
case "month":
diff = Convert.ToDouble((TS.TotalDays/365)*12);
case "day":
diff = Convert.ToDouble(TS.TotalDays);
case "hour":
diff = Convert.ToDouble(TS.TotalHours);
case "minute":
diff = Convert.ToDouble(TS.TotalMinutes);
case "second":
diff = Convert.ToDouble(TS.TotalSeconds);

return diff;

Parminder Singh said...

Hi Shakti,

You can also get DateDiff from http://www.aspcode.net/C-Datediff.aspx

I had searched and finally got solution from this article.

But still I am using function of VB, but if there is limitation of using c#, I think this article is providing an excellent code.

Parminder Singh

Shakti Singh Dulawat said...

I think you must provide your code with result output