FreeBSD FridayProgramming / DevelopmentWPF Databinding TutorialMy Posts

Welcome to my technology learning website. The goal of this site is to learn and retain as much information as possible. I consider this blog my knowledge base and hope that you both find and share knowledge here as well. Also for those wondering, Rhyous is pronounced ‘rī-əs. As in the words ‘Rye‘ and ‘us‘ compounded into a two syllable word.

Please take a moment to subscribe, or setup an RSS feed so you never miss a post.

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?