Search code examples
c#datetimetryparse

Compare DateTime against current system time?


I'm trying to make a C# method to fulfill this user story.

These are the 2 acceptance criteria

  • Start time must be at least one hour later than the current system time.
  • End time must be at last one hour after start time.

Both of the start and end time must be DateTime values, so I can parse it with the TryParse method.

Here's what I have in my code so far:

`


private DateTime datetime;
public DateTime datetimeStart { get; set; }
public DateTime datetimeEnd { get; set; }

while (true) {
    Util.GetInput("Delivery window start (dd/mm/yyyy hh:mm)");
    string userInput = ReadLine();
    
    if(DateTime.TryParse(userInput, out datetime))
    {
        if (datetime.TimeOfDay.Hours - DateTime.Now.TimeOfDay.Hours >= 1) {
            datetimeStart = datetime;
        }
        break;
    }
    else
    {
        WriteLine("\tDelivery window start must be at least one hour in the future.");
    }
}

while (true) {
    Util.GetInput("Delivery window end (dd/mm/yyyy hh:mm)");
    string userInput = ReadLine();
    
    if(DateTime.TryParse(userInput, out datetime))
    {
        if (datetime.TimeOfDay.Hours - datetimeStart.TimeOfDay.Hours >= 1) {
            datetimeEnd = datetime;
        }
        break;
    }
    else
    {
        WriteLine("\tDelivery window end must be at least one hour later than the start.");
    }
}

`

I'm not fully sure how the DateTime type works yet, but later on, I'd need to get an output string with this format: "The pickup window for your order will be 04:00 on 30/10/2022 and 20:00 on 30/10/2022", and just replace the data in the string with values from datetimeStart and datetimeEnd


Solution

  • DateTime provides all the tools to write your conditions in straightforward code:

    one hour later than / after checkTime

    is just

    checkTime.AddHours(1)
    

    and

    someTime must be at least one hour later than / after checkTime

    becomes

    someTime >= checkTime.AddHours(1)
    

    So your code may look something like this:

    ...........................
        if (datetime >= DateTime.Now.AddHours(1)) {
            datetimeStart = datetime;
        }
    ...........................
        if (datetime >= datetimeStart.AddHours(1)) {
            datetimeEnd = datetime;
        }
    ...........................