0

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)

Lie-An
  • 2,563
  • 3
  • 17
  • 20
  • this has good answer http://stackoverflow.com/questions/8183472/how-to-compare-two-nsdate-objects-in-objective-c – Vinodh Nov 15 '13 at 12:16

1 Answers1

3

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).

Wain
  • 118,658
  • 15
  • 128
  • 151
  • And don't forget to reuse the NSDateFormatter because it is expensive. (setFormat counts like a new formatter) – Laszlo Nov 15 '13 at 09:08
  • @Wain, thank you so much! I have done what you've said and it worked perfectly :) – Lie-An Nov 15 '13 at 09:23