iOS6 NSDateFormatter default year

守給你的承諾、 提交于 2019-12-06 09:07:43

问题


Has anyone noticed that iOS6 NSDateFormatter defaults to year 2000 when no year is given while in

iOS6:

[[NSDateFormatter alloc] init] dateFromString: @"7:30am"]

=> 2000 Jan 1st, 7:30am

iOS5:

=> 1970 Jan 1st, 7:30am

Question: 1. Is there a better way to compare two different times? I have this subway app PATH Schedule/Map. The subway times are hardcoded in the database as numSecondsSince1970. I give people the next train arriving by comparing departure times with the current numSecondsSince1970. Right now I am just appending the year 1970 to the time string "2:30am" => "1970 2:30am" but it seems like there is a better way

Thanks!


回答1:


Yes I just noticed this issue. Apparently this bug is reported at Apple, see http://openradar.appspot.com/12358210


Edit: this is how I dealt with this issue in a project I'm working on...

// I use the following code in a category to parsing date strings

- (NSDate *)dateWithPath:(NSString *)path format:(NSString *)format
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
    formatter.dateFormat = format;

    NSString *string = [self valueWithPath:path];
    return [formatter dateFromString:string];
}

// old parsing code that worked fine in iOS 5, but has issues in iOS 6

NSDate *date            = [element dateWithPath:@"datum_US" format:@"yyyy-MM-dd"];
NSDate *timeStart       = [element dateWithPath:@"aanvang" format:@"HH:mm:ss"];
NSTimeInterval interval = [timeStart timeIntervalSince1970];
match.timeStart         = [date dateByAddingTimeInterval:interval];

and the fix ...

// the following code works fine in both iOS 5 and iOS 6

NSDate *date                = [element dateWithPath:@"datum_US" format:@"yyyy-MM-dd"];
NSDate *timeStart           = [element dateWithPath:@"aanvang" format:@"HH:mm:ss"];
NSCalendar *calendar        = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
calendar.timeZone           = [NSTimeZone timeZoneForSecondsFromGMT:0];
NSUInteger units            = NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDateComponents *timeComps = [calendar components:units fromDate:timeStart];
match.timeStart             = [calendar dateByAddingComponents:timeComps toDate:date options:0];


来源:https://stackoverflow.com/questions/12449553/ios6-nsdateformatter-default-year

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