NSDate dateFromString返回null

时间:2010-07-07 19:04:43

标签: iphone objective-c xcode

当应用程序退出时,我将已转换为字符串的日期保存到plist。当viewDidLoad运行时,我试图读回字符串并将其转换回日期。该字符串保存到plist并正确读入但不会转换回日期。我使用的是NSDate date命令给出的标准格式。 Time1始终为null。

输出如下:

time1string = 2010-07-07 13:47:12 -0500
time1 = (null)

代码如下所示:

- (void)applicationWillTerminate:(NSNotification *)notification {
NSMutableArray *array = [[NSMutableArray alloc] init];

[array addObject: [NSString stringWithFormat:@"%@", time1]];

[array writeToFile:[self dataFilePath] atomically:YES];
[array release];

NSLog(@"APP Terminating, Persisting Data");

}

- (void)viewDidLoad {

NSLog(@"View did load");
NSString *filePath = [self dataFilePath];
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
    NSArray *array = [[NSArray alloc] initWithContentsOfFile:filePath];

    NSString *time1string = [array objectAtIndex:1];
    NSLog(@"time1string = %@",time1string);
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-MM-dd hh:mm:ss Z"];
    time1 = [dateFormat dateFromString:time1string];
    NSLog(@"time1 = %@",time1);
    [dateFormat release];
    [array release];

}
UIApplication *app = [UIApplication sharedApplication];
[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(applicationWillTerminate:)
                                             name:UIApplicationWillTerminateNotification 
                                           object:app];
 [super viewDidLoad];

}

1 个答案:

答案 0 :(得分:8)

由于您使用了错误的日期格式,它似乎无法解析。请尝试使用@"yyyy-MM-dd HH:mm:ss Z"hh格式需要1-12范围内的一小时,而HH则使用0-23。

请参阅Locale Data Markup Language以获取有关此处可使用的所有模式的完整参考(通过Data Formatters reference)。