C#如何检查当前是否为字符串的日期是今天? [英] C# How would I check if a date that is currently a string is today?
问题描述
我有一个称为字符串(通用时间)格式的日期,请参见在此处链接了MSDN ,我需要检查此日期是否为今天,是否为X。
I have a date that is in a format called 'String(Generalized-Time)', see MSDN linked here , I need to check if this date is today and if it is do X.
为了使这个稍微复杂一点,在示例4中,我有一个int值,如果int是4,那么我想检查'String(Generalized-Time)'格式的日期是否为最近4天,即int也许是7、24、30等。
To complicate this slightly I have a int that is in this example 4, if the int is 4 then I want to check if the date that is in the 'String(Generalized-Time)' format is in the last 4 days, the int maybe 7, 24, 30 etc.
我该怎么写?我是新手,也非常感谢您的帮助。
How would I write this? I'm a novice and very grateful of the help.
谢谢
推荐答案
像这样:
DateTime dt;
if (DateTime.TryParse(stringValue, out dt) &&
dt.Date == DateTime.Today)
{
// do some stuff
}
要检查过去四天内是否有时间,
To check if it's anytime within the last four days,
DateTime dt;
if (DateTime.TryParse(stringValue, out dt) &&
dt.Date > DateTime.Today.AddDays(-4f) &&
dt < DateTime.Now)
{
// do some stuff
}
或者,作为扩展方法
public static bool WithinPreviousPeriod(this DateTime dt, int daysBack)
{
return dt.Date > DateTime.Today.AddDays(-daysBack))
&& dt < DateTime.Now;
}
这篇关于C#如何检查当前是否为字符串的日期是今天?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!