Find out if an NSDate is today, yesterday, tomorrow

人走茶凉 提交于 2019-12-18 13:01:37

问题


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:

NSDate *myDate = someDate;
if ([myDate isTomorrow]) {
    NSLog("Tomorrow"); 
}

How would you solve it?


回答1:


Check our Erica Sadun's great NSDate extension class: http://github.com/erica/NSDate-Extensions

There are lots of date comparisons, among them exactly what you need :)




回答2:


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.




回答3:


Swift 3

let isToday = Calendar.current.isDateInToday(yourDate)

You can then check the value and proceed accordingly with simply:

if isToday {
    //If true, do this
}

There are similar functions for tomorrow, weekend, and a few others, for example:

let isTomorrow = Calendar.current.isDateInTomorrow(yourDate)

This guide has them all in Objective-C and Swift:



来源:https://stackoverflow.com/questions/4052553/find-out-if-an-nsdate-is-today-yesterday-tomorrow

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!