Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
433 views
in Technique[技术] by (71.8m points)

objective c - Getting Null from NSDateFormatter

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...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It is probably locale-dependent, but with

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

it should work on all devices.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...