dateFromString在ios 6中工作,但不在ios 5中工作 [英] dateFromString working in ios 6 but not in ios 5

查看:96
本文介绍了dateFromString在ios 6中工作,但不在ios 5中工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码适用于iOS 6.0模拟器,但不适用于iOS 5.0

This code working on iOS 6.0 simulator, but not working on iOS 5.0

NSString *unformattedDate = @"2008-09-25T20:41:11.000+00:00";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"];
NSDate *dateFromString = [dateFormatter dateFromString:unformattedDate];
[dateFormatter setDateFormat:@"dd.MM.yy"];
NSLog(@"%@", [dateFormatter stringFromDate:dateFromString]);

可能出现什么问题?

推荐答案

由于在iOS 6中添加了 ZZZZZ 日期格式说明符,因此无法格式化时区为<$ c $的日期c> +99:99 iOS版格式。两个版本都使用 ZZZZ +9999 格式C $ C>。如果你知道你的日期/时间字符串将始终带有冒号的时区,那么你可以去掉冒号。

Since the ZZZZZ date format specifier was added in iOS 6, you can't format dates that have a timezone in the +99:99 format with iOS 5. Both versions do support the +9999 format using ZZZZ. If you know that your date/time strings will always have a timezone with the colon, then you can strip the colon.

NSString *unformattedDate = @"2008-09-25T20:41:11.000+00:00";
NSRange range = [unformattedDate rangeOfString:@":" options:NSBackwardsSearch];
if (range.location != NSNotFound && range.location >= unformattedDate.length - 4) {
    unformattedDate = [unformattedDate stringByReplacingCharactersInRange:range withString:@""];
}
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSLocale *posix = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
[dateFormatter setLocale:locale];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZZZZ"];
NSDate *dateFromString = [dateFormatter dateFromString:unformattedDate];
[dateFormatter setDateFormat:@"dd.MM.yy"];
NSLog(@"%@", [dateFormatter stringFromDate:dateFromString]);

请注意,对于这样的固定格式,您必须将格式化程序的语言环境设置为特殊的en_US_POSIX语言环境。

Note that with fixed formats like this, you must set the formatter's locale to the special "en_US_POSIX" locale.

这篇关于dateFromString在ios 6中工作,但不在ios 5中工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆