-1

In my program, I have dates stored in strings in the form of mm/dd/yyyy. The issue is, I need to know if it is within a week or month of another date.

For example, if I have 12/02/2019, I need an if statement that checks if that date is within 1 week of the computers current date, and another statement that checks if that date is within 1 month of the computers current date.

I am completely lost as to how you would go about doing this, is anyone able to help me?

Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236
leonjacobh
  • 21
  • 4
  • please read through documentation of datetime https://learn.microsoft.com/en-us/dotnet/api/system.datetime.compare?view=netframework-4.8 Try it and when you have errors, please post your code along with issues. – Jawad Dec 06 '19 at 16:02
  • 2
    Dates have no format, they are binary values. You can easily calculate the difference between two dates with `(EndDate-StartDate)` but then you have to decide what `within a month` means. Less than 30 days? This won't work for January. How about January 7 vs February 2? Are they 1 month apart? – Panagiotis Kanavos Dec 06 '19 at 16:05

2 Answers2

2

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;
}
Rufus L
  • 36,127
  • 5
  • 30
  • 43
0

Firstly, you will need to convert your string dates into DateTime objects, using the correct format as you are currently using mm/dd/yyyy:

string myStartDateString = "...";
string myEndDateString = "...";

DateTime startDate = DateTime.ParseExact(myStartDateString, "MM-dd-yyyy", System.Globalization.CultureInfo.InvariantCulture);

DateTime endDate = DateTime.ParseExact(myEndDateString, "MM-dd-yyyy", System.Globalization.CultureInfo.InvariantCulture);

Once you have made that conversion, it's simple arithmetic. Subtract your start date, from your end date and pull the Total Days property from the result.

int differenceInDays = (endDate - startDate).TotalDays;

From here you should be able to make your own calculations to match your criterea, such as "within a month" - do you see that as <30 days?

if(differenceInDays < 30)
{
    //Do Stuff
}
awoodhead
  • 87
  • 8