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

会有一股神秘感。 提交于 2019-11-26 23:25:01

问题


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];
}

回答1:


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];
}



回答2:


23 May 2013 15:37:00 is a 24 hour format string.So the correct date is obtained using the 24 hour format date formatter .Thats it

So use

[fmt setDateFormat:@"dd MMM yyyy HH:mm:ss"];


来源:https://stackoverflow.com/questions/16706293/ios-nsdate-comparison-works-differently-when-the-24-hour-time-in-date-settings-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!