ExtensionMethod.NET Home of 834 C#, Visual Basic, F# and Javascript extension methods

CompareWithoutMinutes

Compares two datettime objects ignoring minutes and seconds

Source

public static int CompareWithoutMinutes(this DateTime source, DateTime toCompare)
{
    source = new DateTime(source.Year, source.Month, source.Day, source.Hour, 0, 0);
    toCompare = new DateTime(toCompare.Year, toCompare.Month, toCompare.Day, toCompare.Hour, 0, 0);

    return source.CompareTo(toCompare);
}

Example

public class Program
{
	public static void Main()
	{
		Console.WriteLine(DateTime.Now.AddMinutes(2).CompareWithoutMinutes(DateTime.Now) == 0); //prints true
		Console.WriteLine(DateTime.Now.AddHours(2).CompareWithoutMinutes(DateTime.Now) == 0); //prints false
	}
}

Author: Skirtek

Submitted on: 2 apr 2020

Language: csharp

Type: System.DateTime

Views: 822