存储“时间”的最佳方式价值
我的类需要两个属性:startTime
和 endTime
。最好使用什么类?我知道有 NSDate,但我只需要存储一个特定时间(00:00-23:59 之间的某个时间),我不需要日期。这里最优雅的解决方案是什么?
My class needs two properties: startTime
and endTime
. What is the best class to use? I know there is NSDate, but I only need to store a specific time (something in between 00:00-23:59), I don't need a date. What is the most elegant solution here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
NSTimeInterval 可能已经足够了。
它将以秒为单位的时间值存储为双精度值。
例如。 5 分钟 = 300.0
NSTimeInterval is probably good enough for this.
It stores a time value in seconds as a double.
Eg. 5 mins = 300.0
我相信最优雅的解决方案,也是您想要的,是
NSTimeInterval
,这是NSDate
构建于其之上的原始类型。NSTimeInterval
是double
的类型定义,是以秒为单位的时间度量。这种原始时间类型没有任何参考日期的概念。NSDate
所做的就是添加参考日期的概念,并将 0.0 时间锚定在 2001 年 1 月 1 日 GMT。没有什么可以阻止您发明自己的参考日期或锚点,例如“无论哪一天的午夜”。您可以做的是添加
NSTimeInterval
的两个属性作为startTime
和endTime
并让它们都使用午夜 作为参考。或者您可以跳过endTime
并选择startTime
和duration
组合。I believe the most elegant solution, and what you want, is
NSTimeInterval
, that is the primitive type thatNSDate
is built on top.NSTimeInterval
is a typedef fordouble
, and is a measurement of time in seconds. This primitive time type do not have any concept of a reference date. WhatNSDate
do is to add this concept of reference date and anchor the 0.0 time at 1 January 2001 GMT. There is nothing that stops you from inventing your own reference date or anchor, like for example "midnight of whatever day there is".What you can do is to add two properties of the
NSTimeInterval
either asstartTime
andendTime
and let them both use midnight as the reference. Or you could skipendTime
and go for astartTime
andduration
combo.有
NSDateComponents< /code>
,“也可用于指定持续时间,例如 5 小时 16 分钟”。
There's
NSDateComponents
, which "can also be used to specify a duration of time, for example, 5 hours and 16 minutes."NSDate
类与 C# 中的DateTime
类类似:都保存日期和时间,但它们可以彼此独立。在 Cocoa 中,您可以比较两个 NSDate 类:The
NSDate
class is similar to theDateTime
class in C#: both hold a date and time, but they can be independent of each other. In Cocoa, you would compare two NSDate classes: