NSDateFormatter, am I doing something wrong or is this a bug?

后端 未结 8 994
-上瘾入骨i
-上瘾入骨i 2020-11-30 06:18

I\'m trying to print out the date in a certain format:

NSDate *today = [[NSDate alloc] init];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]         


        
8条回答
  •  Happy的楠姐
    2020-11-30 06:59

    For those finding this question who want to use NSDateFormatter to parse 24-hour time and are hitting this bug, using NSDateComponents to parse dates and times which have a known format sidesteps this issue:

    NSString *dateStr = @"2010-07-05";
    NSString *timeStr = @"13:30";
    
    NSDateComponents *components = [[NSDateComponents alloc] init];
    components.year = [[dateStr substringToIndex:4] intValue];
    components.month = [[dateStr substringWithRange:NSMakeRange(5, 2)] intValue];
    components.day = [[dateStr substringFromIndex:8] intValue];
    components.hour = [[timeStr substringToIndex:2] intValue];
    components.minute = [[timeStr substringFromIndex:3] intValue];
    
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    
    NSDate *date = [calendar dateFromComponents:components];
    
    [components release];
    [calendar release];
    

提交回复
热议问题