Rob Scott
Rob Scott

Reputation: 8049

Timespan between (2) other Timespan when adding / subtracting minutes C#

Everything works with the exception if I pass in "15 minutes". I receive no errors, it's just that my where clause isn't working 100%. This is b/c I pass in time in 15 minute intervals.

Example:

The parsedTime param is a javascript 24hr format time - in this example is comes in as "00:15".

The problem is when I subtract the -30 minutes from the parsedTime, it puts it at 23:45, and therefore never gets the "00:20".

LINQ query

DateTime parsedTime = DateTime.ParseExact(time, "HH:mm", CultureInfo.InvariantCulture);

var activities = objects
          .Where(x => (x.GetValue<DateTime>("startTime").TimeOfDay 
                      >= parsedTime.AddMinutes(-30).TimeOfDay
                 && x.GetValue<DateTime>("startTime").TimeOfDay 
                     <= parsedTime.AddMinutes(30).TimeOfDay))
          .ToList();

Upvotes: 0

Views: 969

Answers (2)

Matt Johnson-Pint
Matt Johnson-Pint

Reputation: 241525

It sounds like you also need to handle time ranges that could span across midnight, as in the 30 minutes that exists between "23:45" and "00:15". Here's how you can do that:

public static TimeSpan GetTimeDifference(string startTimeOfDay, string endTimeOfDay)
{
    DateTime startDateTime = DateTime.ParseExact(startTimeOfDay, "HH:mm",
        CultureInfo.InvariantCulture, DateTimeStyles.NoCurrentDateDefault);

    DateTime endDateTime = DateTime.ParseExact(endTimeOfDay, "HH:mm",
        CultureInfo.InvariantCulture, DateTimeStyles.NoCurrentDateDefault);

    if (endDateTime >= startDateTime)
    {
        // values do not cross over midnight
        return endDateTime - startDateTime;
    }
    else
    {
        // values cross over midnight
        return endDateTime - startDateTime + TimeSpan.FromHours(24);
    }
}

Or if you prefer something smaller:

public static int GetMinutesDifference(string startTimeOfDay, string endTimeOfDay)
{
    DateTime startDateTime = DateTime.ParseExact(startTimeOfDay, "HH:mm",
        CultureInfo.InvariantCulture, DateTimeStyles.NoCurrentDateDefault);

    DateTime endDateTime = DateTime.ParseExact(endTimeOfDay, "HH:mm",
        CultureInfo.InvariantCulture, DateTimeStyles.NoCurrentDateDefault);

    return (((int)(endDateTime - startDateTime).TotalMinutes + 1440) % 1440);
}

Upvotes: 1

Kyle W
Kyle W

Reputation: 3752

You just want to see if they're within 30 minutes of each other, right? Try using actual timespans

DateTime startTime;
DateTime parsedTime;
TimeSpan difference = startTime - parsedTime;
return difference.TotalMinutes < 30 && difference.TotalMinutes > -30;

Upvotes: 2

Related Questions