Lie-An
Lie-An

Reputation: 2563

Compare time (in format HH:MM:SS) if between two times in IOS

I have the start time and end time in formats HH:mm:ss (24-hour).

I need to compare if the current time is between the start and end time.

I have coded the logic in such a way that it will add 24 hrs to the start time if start time is later than the end time.

if (shift.sShiftStart < shift.sShiftEnd) {
    startTime = shift.sShiftStart;
    startTimeInt = [[shift.sShiftStart substringToIndex:2] integerValue];
    startTimeInt2 = startTimeInt + 24;
    finalStartTime = [startTime stringByReplacingCharactersInRange:NSMakeRange(0, 2) withString:[NSString stringWithFormat:@"%d", startTimeInt2]];
} else {
    finalStartTime = shift.sShiftStart;
}

Now I want to check if my currentTime is between finalStartTime and endTime (all are in HH:mm:ss formats)

Upvotes: 0

Views: 506

Answers (1)

Wain
Wain

Reputation: 119031

Convert the strings to dates (NSDate) and use the compare: method. Don't assume that you can use < on object instances and they will magically know what you want them to do with that (you're actually comparing the pointer values).

Once you have the dates you can add time (also look at the NSDateComponents class).

Upvotes: 3

Related Questions