I need to compare whether date is less than 3 months old.
I will get installation date:
DateTime installdate=DateTime.Parse("1/5/2012 8:12:14 PM");
if ((installdate<DateTime.Now.AddMonths(-3)))
{
// do something
}
Is this the best way to compare the dates?
Thanks.
A few things to think about:
DateTime.TryParseand you should possibly useDateTime.ParseExactorDateTime.TryParseExact, passing in the expected format (and culture)Basically, there are various corner cases around date and time behaviour – you should explicitly think about all of these things (some of which are forced upon you if you use Noda Time instead of
DateTime, btw 🙂Regarding the first point, if the idea is that you get a trial period of three months from the installation date (or something similar), that suggests you should be adding three months to that instead.
I’d also change the variable name and get rid of the redundant parentheses, by the way:
Assuming you’re storing the installation date yourself somewhere, I would try to store it in some form which is less ambiguous – possibly even storing just a “ticks” value instead of a string. But assuming you are storing it yourself, you shouldn’t need to use
TryParse– it makes sense to go “bang” if you can’t parse the value. I’d useParseExact, probably with a standard format specifier of “o” (round trip).