来自YouTube JSON的日期格式化程序

时间:2012-05-30 17:14:36

标签: objective-c ios5

JSON YouTube正在返回此日期格式2010-07-12T08:22:07.000Z我正在努力适应我的需求但没有成功。中间的“T”和.000Z我不知道如何处理它们。

    NSDateFormatter *df = [[NSDateFormatter alloc] init];

    [df setDateFormat:@"yyyy-MM-ddTHH:mm:ss.ZZZZ"];

    NSDate *date = [df dateFromString: [videoDic valueForKey:@"fecha"]];

    [df setDateFormat:@"dd/MM/yyyy"];

    NSString *dateStr = [df stringFromDate:date];

由于

3 个答案:

答案 0 :(得分:16)

根据manual

代码段 publishedAt 日期时间的类型 项目添加到播放列表的日期和时间。该值以ISO 8601(YYYY-MM-DDThh:mm:ss.sZ)格式指定。

根据ISO 8601格式,您可以这样写:

    dateFormatter.timeZone = [NSTimeZone timeZoneWithName:@"UTC"];
    dateFormatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";

SSS 是三个字母的小数秒。 Z 表示UTC时间。

答案 1 :(得分:3)

在通过dateFormatter运行之前尝试剥离字符串。

NSString *formattedString = [[videoDic valueForKey:@"fecha"] stringByReplacingOccurrencesOfString:@"T" withString:@""];

formattedString = [formattedString stringByReplacingCharactersInRange:NSMakeRange(18, 5) withString:@""];

NSDateFormatter *df = [[NSDateFormatter alloc] init];

[df setDateFormat:@"yyyy-MM-ddHH:mm:ss"];

NSDate *date = [df dateFromString: formattedString];

[df setDateFormat:@"dd/MM/yyyy"];

NSString *dateStr = [df stringFromDate:date];

答案 2 :(得分:2)

setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.000'Z'" 为我工作