开发者

NSDate dateFromString returns null

开发者 https://www.devze.com 2023-01-06 19:45 出处:网络
I am saving a date that has been converted to a string to a plist when the app exits. When the viewDidLoad is run I am trying to read the string back in and convert it back to a date. The string saves

I am saving a date that has been converted to a string to a plist when the app exits. When the viewDidLoad is run I am trying to read the string back in and convert it back to a date. The string saves to the plist and reads in correctly but will not convert back to a date. I am using the standard format given by the NSDate date command. Time1 is always null.

The output looks like this:

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

The code looks like this:

- (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(applicatio开发者_运维知识库nWillTerminate:)
                                             name:UIApplicationWillTerminateNotification 
                                           object:app];
 [super viewDidLoad];

}


It looks like it's failing to parse because you're using the wrong date format. Try using @"yyyy-MM-dd HH:mm:ss Z" instead. The hh format requires an hour in the range 1-12, whereas HH uses 0-23.

See the Locale Data Markup Language for the full reference on all of the patterns that can be used here (via Data Formatters reference).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号