DateTime.Compare如何检查日期不到30天?日期、DateTime、Compare

2023-09-02 10:54:02 作者:时间覆盖一切

我想工作,如果一个帐户在不到30天到期。我使用的DateTime比较正确?

 如果(DateTime.Compare(expiryDate,现)小于30)

{
     matchFound = TRUE;
}
 

解决方案   

我使用的DateTime比较正确?

没有。 比较仅能提供约两个日期的相对位置的信息:小于,等于或大于。你需要的是这样的:

  IF((expiryDate  -  DateTime.Now).TotalDays小于30)
    matchFound = TRUE;
 
这些实用的日期函数,你都会了吗

本减去两个的DateTime 秒。其结果是一个TimeSpan对象,它有一个 TotalDays 属性。

此外,有条件可直接写为:

  matchFound =(expiryDate  -  DateTime.Now).TotalDays< 30;
 

没有如果必要的。

I'm trying to work out if an account expires in less than 30 days. Am I using DateTime Compare correctly?

if (DateTime.Compare(expiryDate, now) < 30)

{
     matchFound = true;
}

解决方案

Am I using DateTime Compare correctly?

No. Compare only offers information about the relative position of two dates: less, equal or greater. What you want is something like this:

if ((expiryDate - DateTime.Now).TotalDays < 30)
    matchFound = true;

This subtracts two DateTimes. The result is a TimeSpan object which has a TotalDays property.

Additionally, the conditional can be written directly as:

matchFound = (expiryDate - DateTime.Now).TotalDays < 30;

No if needed.