两个给定 NSDate 之间的 NSDate
我有兴趣创建一种方法来查找当前日期是否落在任何给定日期的特定时间之间。这是一个调度程序,所以我想找到当前时间正在发生什么事件。每天都有相同的时间集:820-900、900-940、940-1020 等。由于这必须在任何给定的一天完成,所以我不知道如何创建具有特定时间的 NSDate。我认为这可以通过 NSTimeInterval 完成,但我不确定如何实例化它。
I am interested in creating a method to find if the current date falls between certain times on any given day. It is for a scheduling program, so I want to find what event is occurring at the current time. Every day has the same set of times: 820-900, 900-940, 940-1020, etc. Since this must be done on any given day I do not know how to create an NSDate with a certain time. I think this might be done with NSTimeInterval but I am not sure how to instantiate that.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这并不完美,但您可以使用 [NSDate Compare:] 来检查两个边界的日期:
或更简单地说:
我确信有更好的方法来进行复杂的日期比较,但这应该可行。
This isn't perfect, but you could use [NSDate compare:] to check your date against both boundaries:
Or more briefly:
I'm sure there's a better way to do complex date comparison, but this should work.
最简单的方法是使用 -timeIntervalSinceReferenceDate 将每个日期转换为 NSTimeInterval 类型的值,这实际上只是一个 double >。
从那里开始,确定某个日期是否在任何给定的两个日期之间只需进行简单的数字比较即可。
如果您需要从日期的字符串表示形式转换为 NSDate 实例,然后检索时间间隔,请使用 NSDateFormatter。
如果您需要从已知日期组件创建日期,请使用 NSCalendar。 (即你知道年份是2010年,月份是4,日期是12,你可以使用NSCalendar的组件通过
-dateFromComponents:
方法生成一个NSDate实例。)。正如 Ben 所指出的,NSCalendar 的组件接口也可用于确定时间和时间。分钟来确定它是否在一个范围内(这似乎是一种非典型用法,因为大多数事件不会每天同时发生......但是......当然......有也是这样做的理由!)
The easiest way to do this would be to use
-timeIntervalSinceReferenceDate
to turn each of your dates into anNSTimeInterval
typed value, which is really just adouble
.From there, determining if a date is in between any given two dates is just a matter of simple numeric comparisons.
If you need to convert from a string representation of a date to an NSDate instance to then retrieve a time interval, use NSDateFormatter.
If you need to create a date from known date components, use NSCalendar. (i.e. you know the year is 2010, the month is 4 and the day is 12, you can use NSCalendar's components to generate an NSDate instance via the
-dateFromComponents:
method.).As Ben indicated, NSCalendar's component interface can also be used to suss out the hour & minute to determine if it is in a range (which would seemingly be an atypical usage in that most events don't happen every day at the same time... but... sure... there are reasons to do that, too!)
看一下 -[NSCalendar 组件:fromDate:]。它可以让您将日期“分解”为各个组成部分,然后在本例中您可以查看小时和分钟。
Take a look at -[NSCalendar components:fromDate:]. It will let you 'decompose' a date into its various components, and then you can, in this instance, look at the hour and minute.