Formatting date strings to NSDate in Objective-C
I've been fighting with some annoying date formats an API has been returning me in my app. I need to convert the following two types of dates into an NSDate I can use around my app.
- SAT 8AM
- MON 8:30PM
At the moment I'm using something similar to this...
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"eee ha"];
NSDate *date = [formatter dateFromString:dateString];
There are two problems with this...
- It seems to put the time back 1 hour (is this some timezone stuff I need to manage)
- It can't handle the
MON 8:30PM
dates...
I'd really appreciate some help with this! T开发者_开发技巧hanks a bunch :-)
As dreamlax points out, if you want it to support multiple date formats, you're going to have to call it with each of those formats until one matches.
As for your mismatch on timezone, the timezone for the formatter defaults to the current time zone of the system. Can you show some code that demonstrates how it's off by an hour? I'm not seeing anything like that.
Of course, this is also a very strange thing to be doing. You do know that "SAT 8AM" means "8a local time on the first Saturday after the Reference date," right? So this would be on Jan 3, 1970. It doesn't mean "the next Saturday after today" or anything like that. I can imagine some strange cases where this would be useful, but I wanted to make sure it's what you really meant to do.
I don't know why it would set the time back an hour, but to get 8:30PM you'll need to use hh:mma. And to handle both 8:30PM and 8PM formats, I would set up an if else condition.
If you are not sure what kind of input you will receive (ex SAT 8AM or MON 8:30AM), I would suggest creating a method that returns an NSDate and takes an NSString as an input. In this method, you would:
- use something like NSRange range = [incomingString rangeOfString:@":"];
- if range == nil, then [formatter setDateFormat:@"eee ha"];
- else [formatter setDateFormat:@"eee hh:mma"];
- finally return [formatter dateFromString:dateString];
精彩评论