I have written the following DateDiff() function in C#. VB.NET users already had it using the Micrsoft.VisualBasic.dll assembly. Now you can use it without referencing this 'ugly' extra assembly.
using System;
namespace ReflectionIT.System {
 publicenum DateInterval {
   Year,
   Month,
   Weekday,
   Day,
   Hour,
   Minute,
   Second
 }
 publicclass DateTimeUtil {
   publicstaticlong DateDiff(DateInterval interval, DateTime date1, DateTime date2){
     TimeSpan ts=date2-date1;
     switch(interval){
       case DateInterval.Year:
         returndate2.Year -date1.Year;
       case DateInterval.Month:
         return(date2.Month -date1.Month)+(12*(date2.Year -date1.Year));
       case DateInterval.Weekday:
         return Fix(ts.TotalDays)/7;
       case DateInterval.Day:
         return Fix(ts.TotalDays);
       case DateInterval.Hour:
         return Fix(ts.TotalHours);
       case DateInterval.Minute:
         return Fix(ts.TotalMinutes);
       default:
         return Fix(ts.TotalSeconds);
     }
   }
   privatestaticlong Fix(double Number){
     if(Number >=0){
       return(long)Math.Floor(Number);
     }
     return(long)Math.Ceiling(Number);
   }
 }
}
namespace ReflectionIT.System {
 publicenum DateInterval {
   Year,
   Month,
   Weekday,
   Day,
   Hour,
   Minute,
   Second
 }
 publicclass DateTimeUtil {
   publicstaticlong DateDiff(DateInterval interval, DateTime date1, DateTime date2){
     TimeSpan ts=date2-date1;
     switch(interval){
       case DateInterval.Year:
         returndate2.Year -date1.Year;
       case DateInterval.Month:
         return(date2.Month -date1.Month)+(12*(date2.Year -date1.Year));
       case DateInterval.Weekday:
         return Fix(ts.TotalDays)/7;
       case DateInterval.Day:
         return Fix(ts.TotalDays);
       case DateInterval.Hour:
         return Fix(ts.TotalHours);
       case DateInterval.Minute:
         return Fix(ts.TotalMinutes);
       default:
         return Fix(ts.TotalSeconds);
     }
   }
   privatestaticlong Fix(double Number){
     if(Number >=0){
       return(long)Math.Floor(Number);
     }
     return(long)Math.Ceiling(Number);
   }
 }
}
All postings/content on this blog are provided "AS IS" with no warranties, and confer no rights. All entries in this blog are my opinion and don't necessarily reflect the opinion of my employer or sponsors. The content on this site is licensed under a Creative Commons Attribution By license.
Blog comments
Raj
06-May-2013 8:48Marco Pellicciotta
13-Nov-2013 4:35Marco Pellicciotta
13-Nov-2013 4:46Marco Pellicciotta
30-Jan-2014 8:32