How to determine if an NSTimeInterval occurred during an arbitrary NSDate?

后端 未结 4 1725
囚心锁ツ
囚心锁ツ 2021-01-07 15:10

I have an NSTimeInterval, and I\'d like to know whether that timestamp falls between the start and end of a date. Basically I need to be able to do something like:



        
4条回答
  •  春和景丽
    2021-01-07 15:58

    An NSTimeInterval is just a number of seconds. To compare it to an NSDate, you need to interpret the time interval relative to some reference point, then create an NSDate with the result, then compare the two NSDates.

    There are two standard reference dates: 2001-01-01 and 1970-01-01 (the latter being “UNIX time”). If neither of those is the correct reference date, use NSCalendar to create an NSDate for the correct reference date, then create your NSDate of interest relative to that.

    Now for the comparison.

    If all you care about is the date on the calendar, then you'll create the NSDate, then use an NSCalendar to get NSDateComponents for the date. Specifically, you'll get the year, month, and day-of-the-month, then compare those.

    There's no need to worry about “start” and “end” times; in fact, if you only care about the date on the calendar, you can ignore the time-of-day entirely.

提交回复
热议问题