C# How would I check if a date that is currently a string is today?

后端 未结 2 1376
-上瘾入骨i
-上瘾入骨i 2021-02-14 00:55

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.

To complicate thi

相关标签:
2条回答
  • 2021-02-14 01:30

    Like this:

       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
       }
    

    or, as an extension method

    public static bool WithinPreviousPeriod(this DateTime dt, int daysBack)
    {
         return dt.Date > DateTime.Today.AddDays(-daysBack))
                 && dt < DateTime.Now;
    }
    
    0 讨论(0)
  • 2021-02-14 01:40
    if(DateTime.Parse(yourString).Date == DateTime.Now.Date )
    {
      //do something
    }
    

    Should see if the day is today. However this is missing error checking (it assumes yourString is a valid datetime string).

    To do the more complicated check you could do:

    DateTime date = DateTime.Parse(yourString);
    int dateOffset = 4;
    
    if(date.Date >= DateTime.Now.AddDays(-dateOffset).Date)
    {
    //this date is within the range!
    }
    
    0 讨论(0)
提交回复
热议问题