DateTime Within Extension Method

I wrote and extension method to DateTime today. I want to call something simple to see if one date is within a two days of another date. There isn’t a within method. I set out to create one and this what I came up with.

Let me know what you think.

using System;
using System.Collections.Generic;

namespace Rhyous.WebFramework.Handlers.Extensions
{
    public enum DateTimeInterval
    {
        Miliseconds,
        Seconds,
        Minutes,
        Hours,
        Days,
        Weeks,
        Months,
        Years
    }

    internal class DateTimeIntervalActionDictionary : Dictionary<DateTimeInterval, Func<double, TimeSpan>>
    {
        #region Singleton

        private static readonly Lazy<DateTimeIntervalActionDictionary> Lazy = new Lazy<DateTimeIntervalActionDictionary>(() => new DateTimeIntervalActionDictionary());

        public static DateTimeIntervalActionDictionary Instance { get { return Lazy.Value; } }

        internal DateTimeIntervalActionDictionary()
        {
            Add(DateTimeInterval.Miliseconds, TimeSpan.FromMilliseconds);
            Add(DateTimeInterval.Seconds, TimeSpan.FromSeconds);
            Add(DateTimeInterval.Minutes, TimeSpan.FromMinutes);
            Add(DateTimeInterval.Hours, TimeSpan.FromHours);
            Add(DateTimeInterval.Days, TimeSpan.FromDays);
            Add(DateTimeInterval.Weeks, (double d) => { return TimeSpan.FromDays(d * 7); });
            Add(DateTimeInterval.Months, (double d) => { return TimeSpan.FromDays(d * 30); });
            Add(DateTimeInterval.Years, (double d) => { return TimeSpan.FromDays(d * 365); });
        }

        #endregion
    }

    public static class DateExtensions
    {
        public static bool IsWithin(this DateTime dateTime, double interval, DateTimeInterval intervalType, DateTime comparisonDateTime)
        {
            TimeSpan allowedDiff = DateTimeIntervalActionDictionary.Instance[intervalType].Invoke(interval);
            TimeSpan diff = dateTime - comparisonDateTime;
            return allowedDiff <= diff;
        }
    }
}

Leave a Reply

How to post code in comments?