Tuesday, May 12, 2009

How to use DateDiff Function in C#

3 comments
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,
Microsoft.VisualBasic.FirstDayOfWeek.System,
Microsoft.VisualBasic.FirstWeekOfYear.System);

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

3 comments:

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);
break;
case "month":
diff = Convert.ToDouble((TS.TotalDays/365)*12);
break;
case "day":
diff = Convert.ToDouble(TS.TotalDays);
break;
case "hour":
diff = Convert.ToDouble(TS.TotalHours);
break;
case "minute":
diff = Convert.ToDouble(TS.TotalMinutes);
break;
case "second":
diff = Convert.ToDouble(TS.TotalSeconds);
break;
}

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.

Thanks,
Parminder Singh

Shakti Singh Dulawat said...

I think you must provide your code with result output