正确使用 NSDateComponents
我一直在关注苹果文档以及这里的一些代码,但我似乎无法让 NSDateComponents 正常工作。
NSCalendar* calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [calendar components:(NSHourCalendarUnit|NSMinuteCalendarUnit) fromDate:dateValue];
[calendar release];
dateValue 是某个日期,我只关心它的时间,时间是 8:00AM。当我检查此后的组件时,小时和分钟都为零。
我也尝试插入这个,因为我读到你需要(虽然不是每个例子都有这个):
[components setCalendar:calendar];
I've been following the apple docs as well as some code on here and I can't seem to get NSDateComponents to work correctly.
NSCalendar* calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [calendar components:(NSHourCalendarUnit|NSMinuteCalendarUnit) fromDate:dateValue];
[calendar release];
dateValue is some date, I only care about the time of it, and the time is 8:00AM. When I check what components is after this, Hour and Minute are both nil.
I also tried inserting this, because I read that you needed to (although not every example has this):
[components setCalendar:calendar];
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
该代码将起作用。也许是因为您试图错误地访问小时和分钟。我这样做了,并在控制台窗口中获取了当前的小时和分钟:
-hour
和-min
返回普通整数,而不是 NSNumber 对象。从 ios8 开始,上面的类常量已被弃用,使用下面的代码:
That code will work. Maybe it's because you're trying to access the hour and minute incorrectly. I did this and got the current hour and minute in the Console window:
-hour
and-minute
return plain integers, not NSNumber objects.From ios8 onwards above class constant is deprecated, use below code: