tags:

views:

371

answers:

2

Hi,

I have a date that is in a format called 'String(Generalized-Time)', see MSDN below, I need to check if this date is today and if it is do X.

http://msdn.microsoft.com/en-us/library/ms684436%28VS.85%29.aspx

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.

Thanks

+13  A: 

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
   }
Charles Bretana
Awesome, how would I check if it was within the last 4 days? Thanks
Joe Majors
Will this take care of the problem on any computer in any locality, or is the parsing related to your system locale? I'm only asking because so many people get into trouble with dates.
spender
DateTime.Parse doesn't handle the "Generalized Time" format, though. Here's an example value from the RFC: 199412161032Z. You'll have to pass in a custom format string.
David
According to the docs for TryParse(s) "The string s is parsed using formatting information in the current DateTimeFormatInfo object, which is supplied implicitly by the current thread culture." I imagine it's probably unsafe to assume this will be good for Generalized Time, even if it "works on your machine". If your app needs to travel, then, like David says, it's time for some sort of IFormatProvider.
spender
Worked great, many thanks.
Joe Majors
+4  A: 
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!
}
Alan
Thanks Alan, I'll try this shortly.
Joe Majors