美文网首页
小记:NSDateFormatter格式化失败

小记:NSDateFormatter格式化失败

作者: 十一岁的加重 | 来源:发表于2017-09-04 15:57 被阅读51次
    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格式化失败

          本文链接:https://www.haomeiwen.com/subject/xpyejxtx.html