¿Qué tal un método de extensión de DateTime para hacer un poco de una interfaz fluida (esos son todos el derecho de la rabia?)
public static class DateTimeTolerance
{
private static TimeSpan _defaultTolerance = TimeSpan.FromSeconds(10);
public static void SetDefault(TimeSpan tolerance)
{
_defaultTolerance = tolerance;
}
public static DateTimeWithin Within(this DateTime dateTime, TimeSpan tolerance)
{
return new DateTimeWithin(dateTime, tolerance);
}
public static DateTimeWithin Within(this DateTime dateTime)
{
return new DateTimeWithin(dateTime, _defaultTolerance);
}
}
Esto se basa en una clase para almacenar el estado y definir una ! sobrecargas de operadores par de == y =:
public class DateTimeWithin
{
public DateTimeWithin(DateTime dateTime, TimeSpan tolerance)
{
DateTime = dateTime;
Tolerance = tolerance;
}
public TimeSpan Tolerance { get; private set; }
public DateTime DateTime { get; private set; }
public static bool operator ==(DateTime lhs, DateTimeWithin rhs)
{
return (lhs - rhs.DateTime).Duration() <= rhs.Tolerance;
}
public static bool operator !=(DateTime lhs, DateTimeWithin rhs)
{
return (lhs - rhs.DateTime).Duration() > rhs.Tolerance;
}
public static bool operator ==(DateTimeWithin lhs, DateTime rhs)
{
return rhs == lhs;
}
public static bool operator !=(DateTimeWithin lhs, DateTime rhs)
{
return rhs != lhs;
}
}
Luego, en su código que puede hacer:
DateTime d1 = DateTime.Now;
DateTime d2 = d1 + TimeSpan.FromSeconds(20);
if(d1 == d2.Within(TimeSpan.FromMinutes(1))) {
// TRUE! Do whatever
}
La clase extensión también alberga una tolerancia estática por defecto por lo que se puede establecer una tolerancia para todo el proyecto y utilizar el método Dentro sin parámetros:
DateTimeTolerance.SetDefault(TimeSpan.FromMinutes(1));
if(d1 == d2.Within()) { // Uses default tolerance
// TRUE! Do whatever
}
Tengo un par de pruebas de unidad, pero eso sería un poco demasiado código para pegar aquí.
una manera ligeramente diferente: if ((fecha1 - date2) .TotalSeconds> 10) – Thomas
Esto debería ser '(dateTime1 - dateTime2) .Duration()
Marius