Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
448 views
in Technique[技术] by (71.8m points)

objective c - iOS NSDate Comparison works differently when the 24-Hour Time in date settings toggles between ON and OFF?

Team, I am comparing the date which is formed from string using NSDateFormatter with the iOS system date. The below statement returns true when the system date time settings is set with 24-Hour Time ON, but the same code returns false when 24-Hour Time OFF.

Problematic Code:

if ([(NSDate*)[NSDate date] compare:currDate] == NSOrderedAscending) {
     // -- Code -- This is executed only when the 4-Hour Time ON
 }

I am confused. The string using which I am getting the date is in 24 hours format. Is this a problem? Or anything else?

Date Formatting Code:

-(NSDate *)getDateFromString:(NSString *)dateString{
    NSDateFormatter* fmt = [[NSDateFormatter alloc] init];
    [fmt setDateFormat:@"dd MMM yyyy hh:mm:ss"];
    [fmt setTimeZone:[NSTimeZone systemTimeZone]];
    [fmt setFormatterBehavior:NSDateFormatterBehaviorDefault];  
    return [fmt dateFromString:dateString];
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

See Apple's Technical Q&A 1480.

You need to set the date formatter's locale to the special locale of en_US_POSIX. You also need to specify a 24-hour hour format - HH, not hh.

-(NSDate *)getDateFromString:(NSString *)dateString{
    NSLocale *posix = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
    NSDateFormatter* fmt = [[NSDateFormatter alloc] init];
    [fmt setLocale:posix];
    [fmt setDateFormat:@"dd MMM yyyy HH:mm:ss"];

    return [fmt dateFromString:dateString];
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...