Il blog di Giuseppe Marchi - SharePoint MVP
NAVIGATION - SEARCH

Metodo DateDiff in C#

Ecco l'equivalente in C# del metodo DateDiff, funzione propria di Visual Basic.

public static long DateDiff(DateInterval interval, DateTime startDate, DateTime endDate)

{
long dateDiffVal = 0;
TimeSpan ts = new TimeSpan(endDate.Ticks - startDate.Ticks);
switch(interval)
{
case DateInterval.Day:
dateDiffVal = (long)ts.Days;
break;
case DateInterval.Hour:
dateDiffVal = (long)ts.TotalHours;
break;
case DateInterval.Millisecond:
dateDiffVal = (long)ts.TotalMilliseconds;
break;
case DateInterval.Minute:
dateDiffVal = (long)ts.TotalMinutes;
break;
case DateInterval.Month:
dateDiffVal = (long)(ts.Days / 30);
break;
case DateInterval.Quarter:
dateDiffVal = (long)((ts.Days / 30) / 3);
break;
case DateInterval.Second:
dateDiffVal = (long)ts.TotalSeconds;
break;
case DateInterval.Week:
dateDiffVal = (long)(ts.Days / 7);
break;
case DateInterval.Year:
dateDiffVal = (long)(ts.Days / 365);
break;
}
return dateDiffVal;
}

L'enumaration DateInterval, va definita in questo modo:

public enum DateInterval

{
Millisecond,
Second,
Minute,
Hour,
Day,
Week,
Month,
Quarter,
Year,
}
blog comments powered by Disqus