如何确定NSDate是否是今天?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (23)

如何检查是否NSDate属于今天?

我曾经使用前10个字符来检查它[aDate description][[aDate description] substringToIndex:10]返回字符串就像"YYYY-MM-DD"这样我比较字符串与返回的字符串[[[NSDate date] description] substringToIndex:10]

有更快和/或更简洁的方法来检查吗?

提问于
用户回答回答于

你可以比较日期组件:

NSDateComponents *otherDay = [[NSCalendar currentCalendar] components:NSCalendarUnitEra | NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:aDate];
NSDateComponents *today = [[NSCalendar currentCalendar] components:NSCalendarUnitEra | NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:[NSDate date]];
if([today day] == [otherDay day] &&
   [today month] == [otherDay month] &&
   [today year] == [otherDay year] &&
   [today era] == [otherDay era]) {
    //do stuff
}
用户回答回答于

在macOS 10.9+和iOS 8+中,NSCalendar / Calendar上有一个方法可以完成这个功能!

- (BOOL)isDateInToday:(NSDate *)date 

所以你只需要做

Objective-C的:

BOOL today = [[NSCalendar currentCalendar] isDateInToday:date];

Swift 3:

let today = Calendar.current.isDateInToday(date)

扫码关注云+社区