ios4 - splitting a date and time from a string int

2019-06-09 13:45发布

问题:

I have a JSON feed coming into my app, one of the fields is a combined date & time string which I need to split into discrete date and time strings for display in a table cell. An example of input from the JSON is:

2012-01-18 14:18:00.

I'm getting a bit confused with the date formatter, and clearly I'm not doing it right - I've tried a number of tutorials but most just seem to show how to format a date.

I've tried something a little like this to get just the time:

NSDictionary *rowData = [self.raceData objectAtIndex:[indexPath row]];     

NSDateFormatter *dateFormat = [[[NSDateFormatter alloc] init] autorelease];
[dateFormat setDateFormat:@"h:mma"];

NSDate *raceDate = [dateFormat dateFromString:[rowData valueForKey:@"race_time"]];        
NSString *raceTime = [dateFormat stringFromDate:raceDate];

but on output raceTime is just null.

Any help appreciated.

回答1:

maybe the format should be more like

[dateFormatter setDateFormat:@"yyyy-MM-dd 'at' HH:mm"];

have a look at http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html

might clear things up abit



回答2:

Right, I have this working - it's probably a bit messy but here's what I did:

NSDictionary *rowData = [self.raceData objectAtIndex:[indexPath row]];     

NSDateFormatter *dateFormat = [[[NSDateFormatter alloc] init] autorelease];
[dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

NSDate* raceDate = nil;
NSError* dateError = nil;
NSRange dateRange = NSMakeRange(0, [[rowData valueForKey:@"race_time"] length]);

[dateFormat getObjectValue:&raceDate forString:[rowData valueForKey:@"race_time"] range:&dateRange error:&dateError];

[dateFormat setDateFormat:@"HH.mm"];
NSString *raceTime = [dateFormat stringFromDate:raceDate];

I can now output raceTime as a standalone time. I had to use getObjectValue:forString:range:error: to parse the original string to a date before changing the formatting and parsing it again.

As I'm using this in a table I suspect I'll need to use a static formatter so it doesn't slow everything down - if anyone can give a best practice on doing that I'd appreciate it.



回答3:

If you are sure that the input string format wouldn't change – you might use something similar to:

NSString *date = nil;
NSString *time = nil;

NSDictionary *rowData = [self.raceData objectAtIndex:[indexPath row]];
NSString *raceTime = [rowData valueForKey:@"race_time"];
NSArray *dateParts = [raceTime componentsSeparatedByString:@" "];
if ([dateParts count] == 2) {
    date = [dateParts objectAtIndex:0];
    time = [dateParts objectAtIndex:1];
}