【问题标题】:Is there a way to combine these 2 methods for DateTime and TimeSpan comparisons有没有办法将这两种方法结合起来进行 DateTime 和 TimeSpan 比较
【发布时间】: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


【解决方案1】:

听起来好像您要比较两个没有时间部分的 DateTime 对象。

请记住,DateTime 和 TimeSpan 都实现了 IEquatable 接口,该接口允许您在任一实例上调用 Compare(...)。

比较没有时间的日期:

DateTime date1 = DateTime.Now;
DateTime date2 = DateTime.Now.AddHours(5);
return date1.Date.Compare(date2.Date) == 0;

对于 DateTime 变量,.Date 属性将返回不带时间的日期。

要比较 TimeSpan,您还可以使用 .Compare 并检查结果是否为 0(表示相等)。

【讨论】:

  • 听起来不错,唯一的差异是我希望比较没有 TICKS 而不是没有 TIME 部分的 DateTime 对象。
  • 你的意思是没有毫秒?请重新阅读上面的 cmets:ticks 不是 DateTime 的一部分,它是不同的表示形式。
  • 抱歉给您带来了困惑,现在知道了。
猜你喜欢
  • 1970-01-01
  • 2019-07-31
  • 1970-01-01
  • 1970-01-01
  • 2022-01-22
  • 2021-03-18
  • 2011-08-24
  • 2015-04-05
  • 1970-01-01
相关资源
最近更新 更多