NSDate between two given NSDates

前端 未结 3 1286
暖寄归人
暖寄归人 2020-12-03 15:57

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 i

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-03 16:17

    The easiest way to do this would be to use -timeIntervalSinceReferenceDate to turn each of your dates into an NSTimeInterval typed value, which is really just a double.

    NSTimeInterval rightNow = [[NSDate date] timeIntervalSinceReferenceDate];
    

    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!)

提交回复
热议问题