[英]How to check if a date has passed in C#?
I'm reading the date expires cookie (2 hours) from database, and I need to check if this date has passed.我正在从数据库中读取 cookie 的过期日期(2 小时),我需要检查该日期是否已过。 What's the best way to do this?
做到这一点的最佳方法是什么?
For example:例如:
public bool HasExpired(DateTime now)
{
string expires = ReadDateFromDataBase(); // output example: 21/10/2011 21:31:00
DateTime Expires = DateTime.Parse(expires);
return HasPassed2hoursFrom(now, Expires);
}
I'm looking for ideas as write the .HasPassed2hoursFrom
method.我正在寻找编写
.HasPassed2hoursFrom
方法的想法。
public bool HasPassed2hoursFrom(DateTime fromDate, DateTime expireDate)
{
return expireDate - fromDate > TimeSpan.FromHours(2);
}
public bool HasExpired(DateTime now)
{
string expires = ReadDateFromDataBase(); // output example: 21/10/2011 21:31:00
DateTime Expires = DateTime.Parse(expires);
return now.CompareTo(Expires.Add(new TimeSpan(2, 0, 0))) > 0;
}
But since DateTime.Now is very fast and you don't need to pass it as function parameter...但是由于 DateTime.Now 非常快,您不需要将其作为函数参数传递...
public bool HasExpired()
{
string expires = ReadDateFromDataBase(); // output example: 21/10/2011 21:31:00
DateTime Expires = DateTime.Parse(expires);
return DateTime.Now.CompareTo(Expires.Add(new TimeSpan(2, 0, 0))) > 0;
}
bool HasPassed2hoursFrom(DateTime now, DateTime expires)
{
return (now - expires).TotalHours >= 2;
}
定期检查日期,看看now.CompareTo(expires) > 0
private enum DateComparisonResult
{
Earlier = -1,
Later = 1,
TheSame = 0
};
void comapre()
{
DateTime Date1 = new DateTime(2020,10,1);
DateTime Date2 = new DateTime(2010,10,1);
DateComparisonResult comparison;
comparison = (DateComparisonResult)Date1.CompareTo(Date2);
MessageBox.Show(comparison.ToString());
}
//Output is "later", means date1 is later than date2
To check if date has passed:要检查日期是否已过:
Source: https://msdn.microsoft.com/en-us/library/5ata5aya%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396来源: https : //msdn.microsoft.com/en-us/library/5ata5aya%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396
你可以只使用运算符
boolean hasExpired = now >= Expires;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.