小记:NSDateFormatter格式化失败

小记:NSDateFormatter格式化失败_第1张图片
image.png

        NSString * brithStr = @"19860504";

        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyyMMdd"];
        //    dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
        NSDate *date = [dateFormatter dateFromString:brithStr];
        if (!date) {
            NSLog(@"date : %@", date.description);
        } else {
            NSLog(@"date = %@", date.description);
        }


解决代码


        NSString * brithStr = @"19860504";
        NSString *dateFormatStr = @"yyyyMMdd";
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        
        //设置转换后的目标日期时区
        NSTimeZone *toTimeZone = [NSTimeZone localTimeZone];
        //转换后源日期与世界标准时间的偏移量
        NSInteger toGMTOffset = [toTimeZone secondsFromGMTForDate:[NSDate date]];
        NSTimeZone * zone = [NSTimeZone timeZoneForSecondsFromGMT:toGMTOffset];
        [formatter setTimeZone:zone];
        NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh"];
        [formatter setLocale:locale];
        [formatter setDateFormat: dateFormatStr];
        NSDate *date2 = [formatter dateFromString:brithStr];
        NSLog(@"----%@---", date2);

http://www.skyfox.org/ios-formatter-daylight-saving-time.html

你可能感兴趣的:(小记:NSDateFormatter格式化失败)