【问题标题】:Different results from new DateTime() and DateTime.Parsenew DateTime() 和 DateTime.Parse 的结果不同
【发布时间】:2015-10-02 20:40:27
【问题描述】:

我在 C# 的单元测试中发现了一些奇怪的行为。

给定以下代码:

var dateTime = DateTime.Parse("01/01/2015");
Assert.AreEqual(dateTime, new DateTime(2015, 1, 1));

我得到一个失败的测试结果:

Expected: 2015-01-01 00:00:00.000
But was:  01/01/2015 00:00:00 +00:00

我尝试在两者上调用 ToString(),传入 CultureInfo.CurrentCulture 并将 DateKind 在新的 DateTime 调用中设置为 Local 和 UTC,但我得到了相同的结果。

为什么这两种方法的结果不一样?

【问题讨论】:

  • using == the result it true。一定是你没有展示的东西。
  • 你的测试框架是什么,Assert.AreEqual 的签名是什么——是 ObjectDateTimeString 还是别的什么?
  • Defo 在 NUnit 中工作,但是 用什么测试呢?可以加个标签吗
  • @DieVeenman 不可能。 DateTime 是 DateTime 并且没有歧义。只有 ToString 会产生不同的结果(潜在的问题可能是混合日期和月份,但在此示例中无关紧要)
  • 只是为了排除其他问题(例如引用相等),Assert.AreEqual(new DateTime(2015, 1, 1), new DateTime(2015, 1, 1)); 会发生什么?

标签: c# datetime


【解决方案1】:

我会试一试:

Assert.IsTrue(DateTime.Compare(DateTime.Parse("01/01/2015"), new DateTime(2015, 1, 1) == 0); 

【讨论】:

  • 虽然这可能会解决问题,但它并不能真正回答问题:“为什么这两种方法不给出相同的结果?”
  • 因为它在日期时间使用 AreEquals 可能不会使用正确的比较器,但是,由于我不确定,我希望得到 OP 的反馈来解释更多
【解决方案2】:

您永远不应该将日期硬编码为字符串。这样做有什么意义?

DateTime.Parse("01/01/2015")

改为这样做:

new DateTime(2015,1,1)

DateTime.Parse 默认使用您当前的文化来创建日期。考虑以下示例:

DateTime.Parse("09/06/2015");

是 6 月 9 日还是 9 月 6 日?根据您的机器文化,您将获得不同的结果。如果您的 DateTime 字符串来自某个地方,那么您可以强制 Parse 方法使用特定的格式/文化。

回到这个问题,它可能与文化有关。

【讨论】:

  • “这样做有什么意义?” 也许单元测试是在文本框中模拟用户输入?
  • @JamesThorpe - 加油。实际上,它是从数据库表中提取值,但是对于单元测试,我正在模拟该位,因为单元测试。
  • @petethepagan-gerbil 您应该为 DateTime.Parse 指定区域性或支持的格式列表以避免混淆。单元测试应该是确定性的
  • @Zbigniew 当我这样做时,我得到了相同的结果(在问题中描述)。
  • @petethepagan-gerbil 我现在无法测试它,因为我没有安装 NUnit,但我假设下面会发生这样的事情: (object)dateTime == (object)new DateTime(2015, 1, 1) 这只是一个猜测,你有没有试过和 Assert.That(d1,Is.EqualTo(d2)) 比较一下?
【解决方案3】:

问题假设简化示例中的第一个变量是 DateTime,而它实际上是 DateTimeOffset。生成该变量的公共方法已更改,我错误地推测返回类型仍然是 DateTime。

所以他们给出不同结果的原因是因为他们不同!

第一课:检查类型,即使你知道它们是什么。 第二课:不要在 SO 问题示例中过于简化。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-09
    • 1970-01-01
    • 2018-05-07
    • 2011-10-22
    • 2020-09-24
    • 1970-01-01
    • 1970-01-01
    • 2014-01-23
    相关资源
    最近更新 更多