ios 如何确定 NSDate 是否是今天?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2331129/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to determine if an NSDate is today?
提问by Seunghoon
How to check if an NSDate
belongs to today?
如何检查一个是否NSDate
属于今天?
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]
.
我曾经使用[aDate description]
. [[aDate description] substringToIndex:10]
像"YYYY-MM-DD"
这样返回字符串,我将字符串与[[[NSDate date] description] substringToIndex:10]
.
Is there more fast and/or neat way to check?
是否有更快速和/或更简洁的检查方法?
Thanks.
谢谢。
回答by Catfish_Man
In macOS 10.9+ & iOS 8+, there's a method on NSCalendar/Calendar that does exactly this!
在 macOS 10.9+ 和 iOS 8+ 中,NSCalendar/Calendar 上有一种方法可以做到这一点!
- (BOOL)isDateInToday:(NSDate *)date
So you'd simply do
所以你只需要做
Objective-C:
目标-C:
BOOL today = [[NSCalendar currentCalendar] isDateInToday:date];
Swift 3:
斯威夫特 3:
let today = Calendar.current.isDateInToday(date)
回答by David Kanarek
You can compare date components:
您可以比较日期组件:
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
}
Edit:
编辑:
I like stefan's method more, I think it makes for a cleaner and more understandable if statement:
我更喜欢 stefan 的方法,我认为它使 if 语句更清晰、更易于理解:
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *components = [cal components:(NSCalendarUnitEra | NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:[NSDate date]];
NSDate *today = [cal dateFromComponents:components];
components = [cal components:(NSCalendarUnitEra | NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:aDate];
NSDate *otherDate = [cal dateFromComponents:components];
if([today isEqualToDate:otherDate]) {
//do stuff
}
Chris, I've incorporated your suggestion. I had to look up what era was, so for anyone else who doesn't know, it distinguishes between BC and AD. This is probably unnecessary for most people, but it's easy to check and adds some certainty, so I've included it. If you're going for speed, this probably isn't a good method anyway.
克里斯,我已经采纳了你的建议。我不得不查一下是什么时代,所以对于不知道的人来说,它区分了 BC 和 AD。这对大多数人来说可能是不必要的,但它很容易检查并增加了一些确定性,所以我把它包括在内。如果你追求速度,这可能不是一个好方法。
NOTEas with many answers on SO, after 7 years this is totally out of date. In Swift now just use .isDateInToday
请注意,与 SO 上的许多答案一样,7 年后这完全过时了。在 Swift 现在只需使用.isDateInToday
回答by Jon
This is an offshoot to your question, but if you want to print an NSDate with "Today" or "Yesterday", use the function
这是您问题的一个分支,但如果您想用“今天”或“昨天”打印 NSDate,请使用该函数
- (void)setDoesRelativeDateFormatting:(BOOL)b
for NSDateFormatter
对于 NSDateFormatter
回答by stefanB
I would try to get today's date normalized to midnight and the second date, normalize to midnight then compare if it is the same NSDate.
我会尝试将今天的日期标准化为午夜和第二个日期,标准化为午夜然后比较它是否是相同的 NSDate。
From an Apple examplehere's how you normalize to midnight today's date, do the same for the second date and compare:
从这里的Apple 示例中,您可以将今天的日期标准化为午夜,对第二个日期执行相同操作并进行比较:
NSCalendar * gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents * components =
[gregorian components:
(NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit)
fromDate:[NSDate date]];
NSDate * today = [gregorian dateFromComponents:components];
回答by Benno Kress
Working Swift 3 & 4 extensionof the suggestion by Catfish_Man:
工作Swift 3 & 4 扩展Catfish_Man 的建议:
extension Date {
func isToday() -> Bool {
return Calendar.current.isDateInToday(self)
}
}
回答by vikingosegundo
No need to juggle with components, eras and stuff.
无需处理组件、时代和其他东西。
NSCalendar provides an method to get the beginning of a certain time unit for an existing date.
NSCalendar 提供了一种方法来获取现有日期的某个时间单位的开始。
This code will get the begin of today and another date and compare that. If it evaluates to NSOrderedSame
, both dates are during the same day — so today.
此代码将获得今天的开始和另一个日期并进行比较。如果计算结果为NSOrderedSame
,则两个日期都在同一天 - 所以今天。
NSDate *today = nil;
NSDate *beginningOfOtherDate = nil;
NSDate *now = [NSDate date];
[[NSCalendar currentCalendar] rangeOfUnit:NSDayCalendarUnit startDate:&today interval:NULL forDate:now];
[[NSCalendar currentCalendar] rangeOfUnit:NSDayCalendarUnit startDate:&beginningOfOtherDate interval:NULL forDate:beginningOfOtherDate];
if([today compare:beginningOfOtherDate] == NSOrderedSame) {
//otherDate is a date in the current day
}
回答by Omar Albeik
extension NSDate {
func isToday() -> Bool {
let cal = NSCalendar.currentCalendar()
var components = cal.components([.Era, .Year, .Month, .Day], fromDate:NSDate())
let today = cal.dateFromComponents(components)!
components = cal.components([.Era, .Year, .Month, .Day], fromDate:self)
let otherDate = cal.dateFromComponents(components)!
return today.isEqualToDate(otherDate)
}
Worked for me on Swift 2.0
在 Swift 2.0 上为我工作
回答by Vojtech Vrbka
Swift version of the best answer:
斯威夫特版本的最佳答案:
let cal = NSCalendar.currentCalendar()
var components = cal.components([.Era, .Year, .Month, .Day], fromDate:NSDate())
let today = cal.dateFromComponents(components)!
components = cal.components([.Era, .Year, .Month, .Day], fromDate:aDate);
let otherDate = cal.dateFromComponents(components)!
if(today.isEqualToDate(otherDate)) {
//do stuff
}
回答by alesplin
You could also check the time interval between the date you have, and the current date:
您还可以检查您拥有的日期和当前日期之间的时间间隔:
[myDate timeIntervalSinceNow]
This will give you the time interval, in seconds, between myDate and the current date/time.
这将为您提供 myDate 和当前日期/时间之间的时间间隔(以秒为单位)。
Link.
链接。
Edit: Note to everyone: I'm well aware that [myDate timeIntervalSinceNow] does not unambiguously determine whether myDate is today.
编辑:请注意:我很清楚 [myDate timeIntervalSinceNow] 不能明确确定 myDate 是否是今天。
I am leaving this answer as is so that if someone is looking for something similar and [myDate timeIntervalSinceNow] is useful, they may find it here.
我将这个答案保留原样,以便如果有人正在寻找类似的东西并且 [myDate timeIntervalSinceNow] 很有用,他们可能会在这里找到它。
回答by ArtOfWarfare
Refer to Apple's documentation entry entitled "Performing Calendar Calculations" [link].
请参阅 Apple 标题为“执行日历计算” [链接]的文档条目。
Listing 13 on that page suggests that to determine the number of midnights between days, you use:
该页面上的清单 13 建议要确定几天之间的午夜数,您可以使用:
- (NSInteger)midnightsFromDate:(NSDate *)startDate toDate:(NSDate *)endDate
{
NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
NSInteger startDay = [calendar ordinalityOfUnit:NSDayCalendarUnit
inUnit:NSEraCalendarUnit
forDate:startDate];
NSInteger endDay = [calendar ordinalityOfUnit:NSDayCalendarUnit
inUnit:NSEraCalendarUnit
forDate:endDate];
return endDay - startDay;
}
You may then determine if two days are the same by using that method and seeing if it returns 0 or not.
然后,您可以通过使用该方法并查看它是否返回 0 来确定两天是否相同。