【问题标题】:How to check if a date occurred more than 1 year ago in C#?如何在 C# 中检查日期是否超过 1 年?
【发布时间】:2020-11-18 10:35:29
【问题描述】:

我有以下代码:

var consentedOnDate = GetConsentedOn(consent.Id);
var declinedOnDate = GetConsentDeclinedOn(consent.Id);
                
var userHasGivenConsentLessThan1YearAgo = consentedOnDate != null && (consentedOnDate.Value - DateTime.Now.Date).TotalDays < -365;
var userHasDeclinedConsentLessThan1YearAgo = declinedOnDate != null && (declinedOnDate.Value - DateTime.Now.Date).TotalDays < -365;

如果 consentedOnDatedeclinedOnDate 从今天开始已经超过 1 年,我希望 userHasGivenConsentLessThan1YearAgouserHasDeclinedConsentLessThan1YearAgo 变量为真,但我的逻辑似乎不起作用 - 有我猜对了吗?不工作是指它在应该为假时说真,反之亦然。

【问题讨论】:

  • 为什么不直接使用var consentOneYearAgo = consentedOnDate &lt; Datetime.Now.AddYears(-1)?(与null比较返回false)
  • @ChrᴉzsupportsMonica 如果同意的OnDate 已经超过一年了?
  • @Jordan1993 如果同意日期早于一年前的现在(!),则返回 true。如果你想让它每天只计算天数,那么今天清晨应该是假的,使用 DateTime.Today。如果您仍然不相信,请尝试一些极端情况,例如 16.11.2020、18.11.2020 00:00:00、18.11.2020 20:00:00 和 25.11.2020,然后查看结果。

标签: c# .net datetime


【解决方案1】:

您可以简化代码并使用内置的 DateTime 方法:

var consentDate = GetConsentedOn(consent.Id);
var consentDeclinedDate = GetConsentDeclinedOn(consent.Id);
                
var isConsentMoreThan1YearAgo = consentDate  < DateTime.Today.AddYears(-1);
var hasDeclinedMoreThan1YearAgo = consentDeclinedDate < DateTime.Today.AddYears(-1);

如果今天是 2020 年 10 月 1 日,如果变量同意日期早于01.10.2020 00:00:00(日期和时间),则返回true,否则返回false。虚假案例包括01.10.2020 00:00:0020.10.2020 00:00:00consentDatenull

还请注意变量的新名称,即以“is”或“has”开头的布尔值。

【讨论】:

  • 尽管注意这对February 29th 的作用,并检查它是否足以满足您的目的。 IE。如果consentDate 是去年的 2 月 28 日,它将返回 false。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-03
  • 1970-01-01
  • 2015-07-24
  • 2011-01-24
相关资源
最近更新 更多