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 DateTime
s. 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 |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用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