ios4 - splitting a date and time from a string into two separate strings

蓝咒 提交于 2019-12-08 12:11:39

问题


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];
}


来源:https://stackoverflow.com/questions/8883628/ios4-splitting-a-date-and-time-from-a-string-into-two-separate-strings

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