iOS NSDateFormatter 在设备上的行为不同
iOS NSDateFormatter behaving differently on device
我有以下代码可以从 NSString
个对象创建 NSDate
个对象。
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"hh:mm aa M/dd/yyyy"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
NSString *day = @"3/26/2015";
NSString *time = @"10:24 PM";
NSString *dateString = [NSString stringWithFormat:@"%@ %@", time, day];
NSDate *date = [dateFormatter dateFromString:dateString];
这段代码在模拟器上运行完美,产生了我所在时区的准确对应时间。但是,当我在 iOS 8 的设备上 运行 时,date
设置为 nil
。
我使用的格式应该符合 this page that is referenced by this Apple Developer page。
如有任何帮助或信息,我们将不胜感激。提前致谢。
编辑:我正在尝试从格式化的 NSString 创建 NSDate 对象,而不是从系统中以预定义的格式获取日期。这个问题的 possible duplicate 可能是密切相关的,但我无法找到适合我的情况的解决方案。
编辑 2:我刚刚注意到只有在设置中启用 24 小时制时才会出现此问题。但是,我无法知道设备所有者使用的是哪种格式,所以我仍然需要解决方案。
使用如此严格的日期格式时,您需要设置区域设置以避免在格式化日期时设备当前区域设置出现问题。否则,NSDateFormatter
将使用设备的区域设置,这说明它仅在您在设置中启用 24 小时制时才会发生。
In all cases, you should consider that formatters default to using the user’s locale (currentLocale
) superimposed with the user’s preference settings. If you want to use the user’s locale but without their individual settings, you can get the locale id from the current user locale (localeIdentifier
) and make a new "standard” locale with that, then set the standard locale as the formatter's locale.
例如,在您的情况下,您可以使用 en_US_POSIX
:
NSLocale *enUSPOSIXLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
dateFormatter.locale = enUSPOSIXLocale;
我有以下代码可以从 NSString
个对象创建 NSDate
个对象。
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"hh:mm aa M/dd/yyyy"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
NSString *day = @"3/26/2015";
NSString *time = @"10:24 PM";
NSString *dateString = [NSString stringWithFormat:@"%@ %@", time, day];
NSDate *date = [dateFormatter dateFromString:dateString];
这段代码在模拟器上运行完美,产生了我所在时区的准确对应时间。但是,当我在 iOS 8 的设备上 运行 时,date
设置为 nil
。
我使用的格式应该符合 this page that is referenced by this Apple Developer page。
如有任何帮助或信息,我们将不胜感激。提前致谢。
编辑:我正在尝试从格式化的 NSString 创建 NSDate 对象,而不是从系统中以预定义的格式获取日期。这个问题的 possible duplicate 可能是密切相关的,但我无法找到适合我的情况的解决方案。
编辑 2:我刚刚注意到只有在设置中启用 24 小时制时才会出现此问题。但是,我无法知道设备所有者使用的是哪种格式,所以我仍然需要解决方案。
使用如此严格的日期格式时,您需要设置区域设置以避免在格式化日期时设备当前区域设置出现问题。否则,NSDateFormatter
将使用设备的区域设置,这说明它仅在您在设置中启用 24 小时制时才会发生。
In all cases, you should consider that formatters default to using the user’s locale (
currentLocale
) superimposed with the user’s preference settings. If you want to use the user’s locale but without their individual settings, you can get the locale id from the current user locale (localeIdentifier
) and make a new "standard” locale with that, then set the standard locale as the formatter's locale.
例如,在您的情况下,您可以使用 en_US_POSIX
:
NSLocale *enUSPOSIXLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
dateFormatter.locale = enUSPOSIXLocale;