The first thing we'll need to do is convert our string representation of a date into a DateTime
object. The DateTime
struct, like many other .NET objects, has a TryParse
method that can be used to attempt to parse a string into an instance of the class. It returns a bool
indicating success, and takes an out
parameter that gets set to the converted value on success, or the default value for the type on failure.
Normally this could be used if the string you've specified matches the date format for the culture that your program is running in. But since you've stated that the string has a specific format, then we should use TryParseExact
instead, which allows us to pass a format string. This may be necessary if your program is running on a machine whose culture defines dates in the format dd/MM/yyyy
(to prevent the month and days from being swapped).
Here's a sample method that will return a DateTime
from your input string:
public static DateTime GetDate(string input)
{
DateTime result;
if (!DateTime.TryParseExact(input, "MM/dd/yyyy", CultureInfo.CurrentCulture,
DateTimeStyles.None, out result))
{
throw new FormatException("date must be in the format: 'MM/dd/yyyy'");
}
return result;
}
Next we can use the DateTime.Today
property to get the current date, after which we can get the difference between the two using the Subtract
method (which returns a TimeSpan
representing the difference), and then compare the TotalDays
property to 7
for a week. For months, we can use the AddMonths
method to determine if the date is within a month from today.
For example:
public static bool IsWithinAWeekBeforeToday(string input)
{
var date = GetDate(input);
return date <= DateTime.Today &&
DateTime.Today.Subtract(date).TotalDays <= 7;
}
public static bool IsWithinAMonthBeforeToday(string input)
{
var date = GetDate(input);
var lastMonth = DateTime.Today.AddMonths(-1);
return date >= lastMonth &&
date <= DateTime.Today;
}