ios4 - 将日期和时间从字符串拆分为两个单独的字符串
我的应用程序中有一个 JSON 提要,其中一个字段是组合日期和日期。时间字符串,我需要将其拆分为离散的日期和时间字符串,以便在表格单元格中显示。 JSON 输入的一个示例是:
2012-01-18 14:18:00.
我对日期格式化程序有点困惑,显然我做得不对 - 我已经尝试了很多教程,但大多数似乎只是展示如何格式化日期。
我尝试过类似这样的方法来获取时间:
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];
但在输出中,raceTime 仅为空。
任何帮助表示赞赏。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
也许格式应该更像是
看看 http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html
可能会澄清一些事情
maybe the format should be more like
have a look at http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html
might clear things up abit
是的,我已经完成了这个工作 - 它可能有点混乱,但这就是我所做的:
我现在可以将 raceTime 作为独立时间输出。我必须使用 getObjectValue:forString:range:error: 将原始字符串解析为日期,然后再更改格式并再次解析它。
当我在表中使用它时,我怀疑我需要使用静态格式化程序,这样它就不会减慢一切 - 如果有人可以提供最佳实践,我将不胜感激。
Right, I have this working - it's probably a bit messy but here's what I did:
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.
如果您确定输入字符串格式不会更改 - 您可以使用类似于以下内容的内容:
If you are sure that the input string format wouldn't change – you might use something similar to: