DateTime.Compare how to check if a date is less than 30 days old?

DateTime.Compare how to check if a date is less than 30 days old?

问题

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;
}

 

回答1

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.

 

回答2

should be

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

note the total days otherwise you'll get werid behaviour

 

 

 

作者:Chuck Lu    GitHub    
posted @   ChuckLu  阅读(30)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2020-04-01 Dependency Injection: Constructor vs Property
2020-04-01 Autofac Mvc
2020-04-01 Sandboxie
2019-04-01 How do I check if a type is a subtype OR the type of an object?
2017-04-01 What are the differences between WebAPI and WebAPI 2
2016-04-01 SuperSocketClientEngine
2015-04-01 .NET_Framework_version_history
点击右上角即可分享
微信分享提示