Skip to content

Instantly share code, notes, and snippets.

@kcargile
Created August 7, 2012 21:21
Show Gist options
  • Save kcargile/3289481 to your computer and use it in GitHub Desktop.
Save kcargile/3289481 to your computer and use it in GitHub Desktop.
.NET approximate equality of two dates by determining if they are within one second of each other.
using System;
namespace Extensions
{
public static class DateTimeExtensions
{
public static bool ApproximatelyEqual(this DateTime t, DateTime obj)
{
return Math.Abs((t - obj).TotalSeconds) < 1;
}
public static bool ApproximatelyEqual(this DateTime? t, DateTime? obj)
{
if (!t.HasValue && !obj.HasValue)
{
return true;
}
if ((t.HasValue && !obj.HasValue) || !t.HasValue && obj.HasValue)
{
return false;
}
return Math.Abs((t.Value - obj.Value).TotalSeconds) < 1;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment