Feedback

C# - Genauigkeit zwischen zwei DateTime-Objekten vergleichen

Veröffentlicht von am 11/22/2015
(0 Bewertungen)
Dieses Code-Snippet in C# hilft einem dabei für zwei unterschiedliche DateTime-Objekte einen Teilvergleich durchzuführen.

Dazu hilft die Enumeration DateTimeUnit, um die Einheiten der DateTime abzubilden.

Die AreUnitsEqual-Methode prüft mit den angegebenen DateTimeUnit`s ob Teile von zwei DateTime-Instanzen gleich sind.

Zum Beispiel könnte man dies beim Filtern von Dateien nutzen, wenn man alle Dateien suchen will die im Jahr 2015, um 17 Uhr erstellt wurden.

Die Methoden geben einen Integer (kleiner, größer, gleich) oder Boolean zurück.
Alle Methoden sind auch als Extensionmethod für DateTime implementiert.

Der Code ist mit der XML-Dokumentation kommentiert.
Unten ist ein Beispiel zum ausprobieren der Methoden.

Viel Spaß beim ausprobieren des Snippets!

static void Main(string[] args)
{
DateTime dt = DateTime.Now;
DateTime dt2 = dt.AddDays(2).AddMinutes(3).AddMilliseconds(100);
List<DateTimeUnit> unitsGo = new List<DateTimeUnit> { DateTimeUnit.Month, DateTimeUnit.Hour, DateTimeUnit.Second };
List<DateTimeUnit> unitsFail = new List<DateTimeUnit> { DateTimeUnit.Month, DateTimeUnit.Hour, DateTimeUnit.Second, DateTimeUnit.MilliSecond };

Console.WriteLine(dt.CompareUnitTo(dt2, DateTimeUnit.Hour));
Console.WriteLine(dt.CompareUnitTo(dt2, DateTimeUnit.MilliSecond));

Console.WriteLine(dt.IsUnitEqualTo(dt2, DateTimeUnit.Year));
Console.WriteLine(dt.IsUnitEqualTo(dt2, DateTimeUnit.Tick));

Console.WriteLine(dt.AreUnitsEqual(dt2, unitsGo));
Console.WriteLine(dt.AreUnitsEqual(dt2, unitsFail));

Console.WriteLine(dt.CompareFromYearTo(dt2, DateTimeUnit.Month));
Console.WriteLine(dt.CompareFromYearTo(dt2, DateTimeUnit.Hour));

Console.WriteLine(dt.IsEqualFromYearTo(dt2, DateTimeUnit.Month));
Console.WriteLine(dt.IsEqualFromYearTo(dt2, DateTimeUnit.Hour));

Console.ReadLine();
}
using System;
using System.Collections.Generic;

namespace DateTimeAccuracyCompare
{
    /// <summary>
    /// Units of da DateTime
    /// </summary>
    public enum DateTimeUnit
    {
        /// <summary>
        /// Represents the unit tick of DateTime instance
        /// </summary>
        Tick,
        /// <summary>
        /// Represents the unit millisecond of DateTime instance
        /// </summary>
        MilliSecond,
        /// <summary>
        ///Represents the unit second of DateTime instance
        /// </summary>
        Second,
        /// <summary>
        /// Represents the unit minute of DateTime instance
        /// </summary>
        Minute,
        /// <summary>
        /// Represents the unit hour of DateTime instance
        /// </summary>
        Hour,
        /// <summary>
        /// Represents the unit day of DateTime instance
        /// </summary>
        Day,
        /// <summary>
        /// Represents the unit month of DateTime instance
        /// </summary>
        Month,
        /// <summary>
        /// Represents the unit year of DateTime instance
        /// </summary>
        Year
    }

    /// <summary>
    /// Static class with static methods to check the accuracy or parts of units between two datetime objects.
    /// </summary>
    public static class DateTimeAccuracy
    {
        /// <summary>
        /// Compares two datetime objects on a given unit and returns 
        /// and integer indicating whether the unit of first instance is less, same or greater than unit of the second instance.
        /// Basic method for all others methods in this class.
        /// </summary>
        /// <param name="t1">The first DateTime to compare.</param>
        /// <param name="t2">The second DateTime to compare.</param>
        /// <param name="unit">The unit to compare between the two datetime objects.</param>
        /// <returns>Returns: an integer to indicate the relativity of t1 and t2. Less than zero unit of t1 is less than t2. Zero unit of t1 and t2 are equal. Greater then zero unit of t2 greater than unit of t1.</returns>
        public static int CompareUnit(DateTime t1, DateTime t2, DateTimeUnit unit)
        {
            switch (unit)
            {
                case DateTimeUnit.Tick:
                    return t1.Ticks.CompareTo(t2.Ticks);
                case DateTimeUnit.MilliSecond:
                    return t1.Millisecond.CompareTo(t2.Millisecond);
                case DateTimeUnit.Second:
                    return t1.Second.CompareTo(t2.Second);
                case DateTimeUnit.Minute:
                    return t1.Minute.CompareTo(t2.Minute);
                case DateTimeUnit.Hour:
                    return t1.Hour.CompareTo(t2.Hour);
                case DateTimeUnit.Day:
                    return t1.Day.CompareTo(t2.Day);
                case DateTimeUnit.Month:
                    return t1.Month.CompareTo(t2.Month);
                case DateTimeUnit.Year:
                    return t1.Year.CompareTo(t2.Year);
                default:
                    return t1.CompareTo(t2);
            }
        }

        /// <summary>
        /// Compare a unit of two DateTime-object returning equality as a boolean.
        /// </summary>
        /// <param name="t1">The first DateTime to compare.</param>
        /// <param name="t2">The second DateTime to compare.</param>
        /// <param name="unit">The unit to compare between the two datetime objects.</param>
        /// <returns>Returns: true when unit of instance t1 and t2 are equal or false if not.</returns>
        public static bool IsUnitEqual(DateTime t1, DateTime t2, DateTimeUnit unit)
        {
            return CompareUnit(t1, t2, unit) == 0;
        }

        /// <summary>
        /// Compares two instances of datetimes wheather the given units are equal between them.
        /// </summary>
        /// <param name="t1">The first DateTime to compare.</param>
        /// <param name="t2">The second DateTime to compare.</param>
        /// <param name="units">The units to compare between the two datetime objects.</param>
        /// <returns>Returns: true if all units between t1 and t2 instances are euqal, else false if not.</returns>
        public static bool AreUnitsEqual(DateTime t1, DateTime t2, List<DateTimeUnit> units)
        {
            if (units.Count == 0)
                return CompareUnit(t1, t2, DateTimeUnit.Tick) == 0;

            foreach (var unit in units)
            {
                if (!IsUnitEqual(t1, t2, unit))
                    return false;
            }
            return true;
        }

        /// <summary>
        /// Compares two DateTime-Objects by units starting by year until the given unit and returns an integer wheather part of instance t1 is less, same or greater than instance t2.
        /// </summary>
        /// <param name="t1">The first DateTime to compare.</param>
        /// <param name="t2">The second DateTime to compare.</param>
        /// <param name="accuracy">The accuracy as unit to compare between the two datetime objects.</param>
        /// <returns>Returns: an integer -1 when t1 is less, 0 when same or 1 when greater than t2.</returns>
        public static int CompareFromYearUntil(DateTime t1, DateTime t2, DateTimeUnit accuracy)
        {
            for (int i = (int)DateTimeUnit.Year; i >= (int)accuracy; i--)
            {
                int result = CompareUnit(t1, t2, (DateTimeUnit)i);
                if (result != 0)
                    return result;
            }
            return 0;
        }

        /// <summary>
        /// Compares two DateTime-Objects by units starting by year until the given unit and returns a boolean if part to compare of t1 and t2 are equal or not.
        /// </summary>
        /// <param name="t1">The first DateTime to compare.</param>
        /// <param name="t2">The second DateTime to compare.</param>
        /// <param name="accuracy">The accuracy as unit to compare between the two datetime objects.</param>
        /// <returns>Returns: true if part of units to compare of t1 and t2 are equal or false if not.</returns>
        public static bool IsEqualFromYearUntil(DateTime t1, DateTime t2, DateTimeUnit accuracy)
        {
            return CompareFromYearUntil(t1, t2, accuracy) == 0;
        }
    }
}

namespace DateTimeAccuracyCompare
{
    namespace Extentions
    {
        /// <summary>
        /// This is a extension class to implement all methods from the DateTimeAccuracy class as extensions to DateTime.
        /// </summary>
        public static class DateTimeAccuracyExtensions
        {
            public static int CompareUnitTo(this DateTime dt, DateTime value, DateTimeUnit unit)
            {
                return DateTimeAccuracy.CompareUnit(dt, value, unit);
            }

            public static bool IsUnitEqualTo(this DateTime dt, DateTime value, DateTimeUnit unit)
            {
                return DateTimeAccuracy.IsUnitEqual(dt, value, unit);
            }

            public static bool AreUnitsEqual(this DateTime dt, DateTime value, List<DateTimeUnit> units)
            {
                return DateTimeAccuracy.AreUnitsEqual(dt, value, units);
            }

            public static int CompareFromYearTo(this DateTime dt, DateTime value, DateTimeUnit accuracy)
            {
                return DateTimeAccuracy.CompareFromYearUntil(dt, value, accuracy);
            }

            public static bool IsEqualFromYearTo(this DateTime dt, DateTime value, DateTimeUnit accuracy)
            {
                return DateTimeAccuracy.IsEqualFromYearUntil(dt, value, accuracy);
            }
        }
    }
}


Abgelegt unter DateTime, Extensions.

Kommentare zum Snippet

 

Logge dich ein, um hier zu kommentieren!