Find out if an NSDate is today, yesterday, tomorrow

前端 未结 3 1662
北恋
北恋 2020-12-31 05:47

With the iOS SDK I need to find an easy and secure way to see if an NSDate is today, yesterday, tomorrow. What I\'m looking for is something like this in pseudo code:

<
3条回答
  •  清歌不尽
    2020-12-31 06:02

    I understand that this is pretty old, but I want to bring the answer up to date (as I didn't see anyone else post a more up to date answer).

    Since iOS 8.0 you have a bunch of functions that you can use for date comparison:

    • compareDate:toDate:toUnitGranularity:
    • isDate:equalToDate:toUnitGranularity:
    • isDate:inSameDayAsDate:
    • isDateInToday:
    • isDateInTomorrow:
    • isDateInWeekend:
    • isDateInYesterday:

    See below example:

    NSDate *today = [NSDate new];
    NSCalendar* calendar = [NSCalendar currentCalendar];
    
    BOOL isToday = [calendar isDateInToday:today];
    BOOL isYesterday = [calendar isDateInYesterday:today];
    

    isToday will be YES.

    isYesterday will be NO, given that we gave it todays date.

    See Apple's Documentation for further reading.

提交回复
热议问题