NSDate:正确的工作方式与一天的时间? [英] NSDate: Right way to work with time of day?

查看:93
本文介绍了NSDate:正确的工作方式与一天的时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用指定一天中的时间(例如上午10:30)的时间表。我不知道日期,但是。我将把这些值存储在 NSDictionary 中,并希望以一种直接的方式处理它们。

I am working with a schedule that specifies times of day, such as 10:30 AM. I do not know the dates, however. I'm going to store these as values in a NSDictionary and would like to deal with them in a straightforward way.

我不能使用 NSDate ,因为我没有日期。至少不是以直接的方式。

I can't use NSDate, since I don't have a date. At least, not in a straightforward way.

另一种似乎很明显的方法是 NSTimeInterval ,但看起来像它可能是一个非常微妙的错误的来源。我特别考虑夏令时(这个星期在我心里是有原因的)。

The other way that seems obvious is NSTimeInterval, but that looks like it's probably a source of very subtle errors. I'm thinking in particular of daylight savings time (which is on my mind this week for some reason!).

除此之外,唯一真正的春天或者在 NSNumber (例如小时* 60 +分钟)中对其进行编码。当然,这两个工作都很好,但似乎我发明了一个方形轮,我确信已经有一个圆形的地方。

Other than that, the only things that really spring to mind are keeping it in a formatted string or encoding it in a NSNumber (like hours * 60 + minutes). Both of which would work out fine, of course, but seem like I'm inventing a square wheel where I'm sure there's already a round one somewhere.

什么是最少是使用Cocoa处理原始时间的方式?

What's the least against the grain way of dealing with raw times using Cocoa?

推荐答案

简短的回答是没有内置的机制存储时间,所以只是使用任何最方便你。我使用自己的编码和解析代码(例如,22:00)过去使用字符串,因为它们易于阅读和调试,但存储秒或分钟过去的午夜没有什么错误,建议。请记住,你必须自己做数学。

The short answer is that there's no built-in mechanism for storing time-of-day, so just use whatever is most convenient to you. I've used strings in the past using my own encoding and parsing code, (e.g., "22:00") because they're easy to read and debug, but there's nothing wrong with storing seconds or minutes past midnight as you suggest. Just remember that you'll have to do the math yourself.

无论如何,你需要单独的年,月,日,小时,分钟和秒值,以便您可以使用NSCalendar的 -dateFromComponents:方法从NSDateComponents构造NSDate。

How ever you do it, you will need separate year, month, day, hour, minute, and second values so that you can construct an NSDate from NSDateComponents, using NSCalendar's -dateFromComponents: method.

说,你不能通过添加小时和分钟为现有 NSDate 设置时间,因为如果你跨越DST边界,得到你期望的值。 (但是,我假设您仍然可以添加日期和月份组件,而不必担心DST)

And as others have said, you cannot set the time-of-day by adding hours and minutes to an existing NSDate because if you cross a DST boundary you won't get the value you expect. (However, I assume you can still add day and month components without worrying about DST)

这篇关于NSDate:正确的工作方式与一天的时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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