Advertisement
Advertisement

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 PureSourceCode.System
{
public enum DateInterval
{
Year,
Month,
Weekday,
Day,
Hour,
Minute,
Second
}

public class DateTimeUtil
{
public static long DateDiff(DateInterval interval, DateTime date1, DateTime date2)
{
TimeSpan ts = date2 - date1;
switch (interval)
{
case DateInterval.Year:
return date2.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);
}
}

private static long Fix(double Number)
{
if (Number >= 0)
{
return (long)Math.Floor(Number);
}
return (long)Math.Ceiling(Number);
}
}
}

Advertisement
Advertisement

By Enrico

My greatest passion is technology. I am interested in multiple fields and I have a lot of experience in software design and development. I started professional development when I was 6 years. Today I am a strong full-stack .NET developer (C#, Xamarin, Azure)

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.