Wednesday, May 9, 2012

C# DateTime utility extension methods

A lot of times we find the need for utility methods to operate on DateTime type in C# .net. Here is a utility class that I implemented which has some of the utility methods I think might come in handy. This class is ready to be consumed as is. Just put it in an appropriate namespace and use that namespace in your class/program. Feel free to post enhancements to this class that you think might come in handy.


public static class DateTimeExt
{

public static bool IsWithinLastXDays(this DateTime dateTime, int days)
{
return
DateTime.Now.AddDays(-days) <= dateTime &&
dateTime <= DateTime.Now;
}

public static bool IsWithinLastXMinutes(this DateTime dateTime, int minutes)
{
return
DateTime.Now.AddMinutes(-minutes) <= dateTime &&
dateTime <= DateTime.Now;
}

public static int DaysSince(this DateTime dateTime)
{
return
new TimeSpan(DateTime.Now.Ticks - dateTime.Ticks).Days;
}


        public static int YearsOld(this DateTime dateTime)
        {
                        DateTime current = DateTime.Now;

int age = current.Year - dateTime.Year;

if (age > 0)
{
age -= Convert.ToInt32(current.Date < dateTime.Date.AddYears(age));
}
else
{
age = 0;
}
return age;

        }

        public static DateTime MinSqlDateTime()
        {
            return new DateTime(1900, 1, 1);
        }


public static DateTime FindFollowingDayOfWeek(this DateTime currentDate, DayOfWeek day)
{
int currentDay = (int)currentDate.DayOfWeek;
int seekDay = (int)day;
int daysToAdd = 0;
if (seekDay <= currentDay)
{
daysToAdd = (7 - currentDay) + seekDay;
}
else
{
daysToAdd = (seekDay - currentDay);
}

return currentDate.AddDays(daysToAdd);
}

public static DateTime FindPreviousDayOfWeek(this DateTime currentDate, DayOfWeek day)
{
int currentDay = (int)currentDate.DayOfWeek;
int seekDay = (int)day;
int daysToAdd = 0;
if (seekDay <= currentDay)
{
daysToAdd = (7 - currentDay) + seekDay;
}
else
{
daysToAdd = (seekDay - currentDay);
}
daysToAdd = daysToAdd - 7;

return currentDate.AddDays(daysToAdd);
}
}

Here is a unit test class (using nUnit) that shows the usage of the class above:
        [TestFixture]
        public class Test
        {
                        [Test]
                        public void IsWithinLastXDaysTest()
                       {
                             Assert.IsFalse(DateTime.Now.AddDays(4).IsWithinLastXDays(5));
                             Assert.IsTrue(DateTime.Now.IsWithinLastXDays(5));
                             Assert.IsTrue(DateTime.Now.AddDays(-4).IsWithinLastXDays(5));
                             Assert.IsTrue(DateTime.Now.AddDays(-5).IsWithinLastXDays(5));
                             Assert.IsFalse(DateTime.Now.AddDays(-6).IsWithinLastXDays(5));
                       }             
        }
Make Custom Gifts at CafePress

No comments:

Post a Comment