如何确定 NSDate 是否是今天? [英] How to determine if an NSDate is today?
问题描述
如何检查一个NSDate
是否属于今天?
How to check if an NSDate
belongs to today?
我曾经使用 [aDate description]
中的前 10 个字符来检查它.[[aDate description] substringToIndex:10]
返回类似 "YYYY-MM-DD"
的字符串,所以我将字符串与 [[[NSDate] 返回的字符串进行了比较date] description] substringToIndex:10]
.
I used to check it using first 10 characters from [aDate description]
. [[aDate description] substringToIndex:10]
returns string like "YYYY-MM-DD"
so I compared the string with the string returned by [[[NSDate date] description] substringToIndex:10]
.
是否有更快速和/或更简洁的检查方法?
Is there more fast and/or neat way to check?
谢谢.
推荐答案
在 macOS 10.9+ &iOS 8+,NSCalendar/Calendar 上有一个方法可以做到这一点!
In macOS 10.9+ & iOS 8+, there's a method on NSCalendar/Calendar that does exactly this!
- (BOOL)isDateInToday:(NSDate *)date
所以你只需要做
目标 C:
BOOL today = [[NSCalendar currentCalendar] isDateInToday:date];
Swift 3:
let today = Calendar.current.isDateInToday(date)
这篇关于如何确定 NSDate 是否是今天?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!