【发布时间】:2014-11-20 05:28:59
【问题描述】:
有没有办法将DateTime(比较日期时间时忽略刻度)和TimeSpan这两种方法与通用参数类型进行比较并整合逻辑?
private bool AreDateTimesEqual(DateTime? firstDateTime, DateTime? seconDateTime)
{
bool compareResult = false;
if (firstDateTime.HasValue && seconDateTime.HasValue)
{
firstDateTime = firstDateTime.Value.AddTicks(-firstDateTime.Value.Ticks);
seconDateTime = seconDateTime.Value.AddTicks(-seconDateTime.Value.Ticks);
compareResult = DateTime.Compare(firstDateTime.GetValueOrDefault(), seconDateTime.GetValueOrDefault()) == 0;
}
else if (!firstDateTime.HasValue && !seconDateTime.HasValue)
{
compareResult = true;
}
return compareResult;
}
private bool AreTimeSpansEqual(TimeSpan? firstTimeSpan, TimeSpan? secondTimeSpan)
{
bool compareResult = false;
if (firstTimeSpan.HasValue && secondTimeSpan.HasValue)
{
compareResult = TimeSpan.Compare(firstTimeSpan.GetValueOrDefault(), secondTimeSpan.GetValueOrDefault()) == 0;
}
else if (!firstTimeSpan.HasValue && !secondTimeSpan.HasValue)
{
compareResult = true;
}
return compareResult;
}
【问题讨论】:
-
firstDateTime.Value.AddTicks(-firstDateTime.Value.Ticks);最终不只是 0 吗? -
不,它给出了不带刻度的 firstDateTime 值,当分配回 firstDateTime 时,它将覆盖该值。
-
您确实意识到
Ticks不仅仅是DateTime的小数部分吗?这是全部价值! -
我认为您不了解 .Ticks 属性是什么。现在不是时候。它是从 0001 年 1 月 1 日午夜 12:00:00 到您的 DateTime 的总滴答声。
标签: c# datetime datetime-comparison