NSDate / NSDateFormatter - 仅存储时间,而不是日期? [英] NSDate/NSDateFormatter - Storing only time, not date?

查看:69
本文介绍了NSDate / NSDateFormatter - 仅存储时间,而不是日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在四处寻找,但我没有看到任何可以解决这个问题的事情,所以我希望有人可以帮我解决这个问题。我想要做的是使用NSDate变量(在核心数据中)来存储时间,而不是日期和时间,但只是时间格式为HH:MM:SS;

I've been looking around but I haven't seen anything that addresses this so I'm hoping someone can help clear this up for me. What I am trying to do is use an NSDate variable(in core data) to store a time, not date and time, but just time in the format HH:MM:SS;

在查看NSDateFormatter类引用和提供的示例代码之后,我能够调整它并认为我的代码应该如下所示:

After looking at the NSDateFormatter class reference and the sample code provided I was able to tweak it and think that my code should look something like the following:

NSDateFormatter *timeOfArrival = [[NSDateFormatter alloc] init];
[timeOfArrival setTimeStyle:NSDateFormatterLongStyle];
[timeOfArrival setDateStyle:NSDateFormatterNoStyle];
[timeOfArrival setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"] autorelease]];

NSString *etaStr = [attributeDict objectForKey:@"cumulativeTime"];
NSLog(@"%@", etaStr);
checkpoint.eta = [timeOfArrival dateFromString:etaStr];

直到我尝试从我的字符串创建我的NSDate对象的最后一行的所有内容都有效,但之后那个,checkpoint.eta仍然是零。

Everything up until the last line where I try to create my NSDate object from my string works, but after that, checkpoint.eta is still nil.

etaStr正确输出我的预期值,例如00:14:00,但我不确定我是什么做错了。

etaStr correctly outputs my expected value, 00:14:00, for example, but I'm not sure what I'm doing wrong.

推荐答案

我最终没有使用NSDate / NSDateFormatter,因为我无法让它正常工作。我的解决方案包括将我的时间字符串解析为小时,分钟和秒。我最终最终将所有内容转换为秒,并以这种方式存储它们。

I ended up not using NSDate/NSDateFormatter because I couldn't get it to work properly. My solution consisted of parsing my time string into a hours, minutes, and seconds. I eventually ended up converting everything to seconds, and storing them in that way.

这篇关于NSDate / NSDateFormatter - 仅存储时间,而不是日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆