了解NSDate是今天,昨天,明天

时间:2010-10-29 14:00:26

标签: iphone ios nsdate

使用iOS SDK,我需要找到一种简单安全的方法来查看NSDate今天,昨天,明天。我正在寻找的是伪代码中的类似内容:

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

你会如何解决它?

3 个答案:

答案 0 :(得分:38)

我知道这已经很老了,但我想把答案更新(因为我没有看到其他人发布更新的答案)。

从iOS 8.0开始,您可以使用许多功能进行日期比较:

  • compareDate:TODATE:toUnitGranularity:
  • 而isDate:equalToDate:toUnitGranularity:
  • 而isDate:inSameDayAsDate:
  • isDateInToday:
  • isDateInTomorrow:
  • isDateInWeekend:
  • isDateInYesterday:

见下面的例子:

NSDate *today = [NSDate new];
NSCalendar* calendar = [NSCalendar currentCalendar];

BOOL isToday = [calendar isDateInToday:today];
BOOL isYesterday = [calendar isDateInYesterday:today];

今天将是。

因为我们今天给了它,所以昨天将是NO。

有关详细信息,请参阅Apple's Documentation

答案 1 :(得分:33)

查看我们的Erica Sadun出色的NSDate extension课程:http://github.com/erica/NSDate-Extensions

有很多日期比较,其中正是你需要的:)

答案 2 :(得分:3)

Swift 3

let isToday = Calendar.current.isDateInToday(yourDate)

然后您可以检查该值并继续相应地执行:

if isToday {
    //If true, do this
}

明天,周末和其他一些人也有类似的功能,例如:

let isTomorrow = Calendar.current.isDateInTomorrow(yourDate)

This guide将它们全部放在Objective-C和Swift中:

enter image description here

相关问题