开发者

iphone - comparing two times

how do i , given two times in HH:mm:ss format compare then and determine which is the later time.

开发者_高级运维

12:00:00 & 14:00:00

how do i determine that 14:00:00 is the later time


Look into NSDateFormatter (initWithDateFormat:allowNaturalLanguage:, dateWithString) for transforming your input strings into NSDate instances. Then use methods like earlierDate: or compare: on the resulting NSDates.


If you're working within the same time zones (yeah, that adds complications), then it's generally easiest to convert those strings into NSDate objects and then compare them directly. There's some detail on convert to and from NSDate and NSCalendar objects at http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/DatesAndTimes/DatesAndTimes.html

There is another SO question with the "how to do this" at Converting a string to an NSDate


To add to the previous answers, if you actually have two NSStrings with @"12:00:00" and @"14:00:00" you could get away with:

NSString *timeA, *timeB; // <-- these are your two times in the format 
    // HH:mm:ss where HH is 24h format (no am/pm) and midnight is 00 
    // and you always have two digits (i.e. 12:3:50 for 3m50s past 12 is 
    // always shown as 12:03:50) ...
BOOL timeAIsSooner = [[[timeA componentsSeparatedByString:@":"] 
        componentsJoinedByString:@""] intValue]
    < [[[timeB componentsSeparatedByString:@":"] 
        componentsJoinedByString:@""] intValue];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜