Getting Null from NSDateFormatter

北城余情 提交于 2019-11-27 07:23:52

问题


I am trying to convert a String into NSDate, but I am getting Null.

Sample String Input is = 8/8/2013 12:32:22 PM

Code:

[self.dateFormat setDateFormat:@"MM/dd/yyyy hh:mm:ss a"];
NSLog(@"Date %@", [[communications objectAtIndex:x] objectForKey:@"dateUpdated"]);
NSDate *date = [[NSDate alloc] init];
date = [self.dateFormat dateFromString:[[communications objectAtIndex:x] objectForKey:@"dateUpdated"]];
NSLog(@"Date from NSDate %@", [self.dateFormat stringFromDate:date]);

What am I doing wrong?

Sample NSLog Output

2013-08-15 13:01:59.409 HD[478:907] Date 8/8/2013 12:32:22 PM
2013-08-15 13:01:59.412 HD[478:907] Date from NSDate (null)  
2013-08-15 13:01:59.418 HD[478:907] Date 8/12/2013 9:45:18 AM
2013-08-15 13:01:59.419 HD[478:907] Date from NSDate (null)
2013-08-15 13:01:59.421 HD[478:907] Date 8/12/2013 9:45:20 AM
2013-08-15 13:01:59.423 HD[478:907] Date from NSDate (null)
2013-08-15 13:01:59.430 HD[478:907] Date 8/12/2013 4:10:49 PM
2013-08-15 13:01:59.431 HD[478:907] Date from NSDate (null)

Note: What's really strange is that if I run the same code on Simulator it works fine and most devices. For some reason, if I run it on a handful of devices that are all up to date, it returns null...


回答1:


It is probably locale-dependent, but with

[self.dateFormat setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];

it should work on all devices.




回答2:


Make these changes, then report back:

[self.dateFormat setDateFormat:@"MM/dd/yyyy hh:mm:ss a"];
NSLog(@"Date %@", [[communications objectAtIndex:x] objectForKey:@"dateUpdated"]);
NSDate *date = [self.dateFormat dateFromString:[[communications objectAtIndex:x] objectForKey:@"dateUpdated"]];
NSLog(@"Date from NSDate %@", [self.dateFormat stringFromDate:date]);

Also make sure

if (!self.dateFormat) {
    self.dateFormat = [[NSDateFormatter alloc] init];
}



回答3:


First of all, try to check if your code is working in single pieces. For instance, try to see the NSString that is going to be used in -dateFromString: method is in the desired format. Also, in order to check if your code is working, you're reverting the operation from NSDate to NSString.

I have tried the following code and it works well. So definitely, your error is somewhere else, but not in the date format itself. Check also if your NSDateFormatter was properly initilized.

NSString *dateString = @"8/8/2013 12:32:22 PM";

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MM/dd/yyyy hh:mm:ss a"];

NSDate *date = [dateFormatter dateFromString:dateString];

NSLog(@"date = %@", date);


来源:https://stackoverflow.com/questions/18257842/getting-null-from-nsdateformatter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!