ios Cocoa-Touch:如何查看两个 NSDate 是否在同一天?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1561554/
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
Cocoa-Touch: How do I see if two NSDates are in the same day?
提问by Prody
I need to know if two NSDate instances are both from the same day.
我需要知道两个 NSDate 实例是否都来自同一天。
Is there an easier/better way to do it than getting the NSDateComponents and comparing day/month/year?
有没有比获取 NSDateComponents 和比较日/月/年更简单/更好的方法?
采纳答案by fbrereto
NSDateComponents sounds like the best bet to me. Another tactic to try is toll-free-bridging it to a CFDate, then using CFDateGetAbsoluteTime and doing a subtraction to get the amount of time between the two dates. You'll have to do some additional math to figure out if the time difference lands the dates on the same day, however.
NSDateComponents 对我来说听起来是最好的选择。另一种尝试的策略是免费将其桥接到 CFDate,然后使用 CFDateGetAbsoluteTime 并进行减法以获得两个日期之间的时间量。但是,您必须做一些额外的数学运算才能确定时差是否将日期落在同一天。
回答by progrmr
If you are targeting iOS 8 (and OS X 10.9) or later, then Joe's answeris a better solution using a new method in NSCalendar just for this purpose:
如果您的目标是iOS 8(和 OS X 10.9)或更高版本,那么Joe 的答案是一个更好的解决方案,在 NSCalendar 中为此目的使用一种新方法:
-[NSCalendar isDate:inSameDayAsDate:]
For iOS 7 or earlier: NSDateComponents is my preference. How about something like this:
对于 iOS 7 或更早版本: NSDateComponents 是我的偏好。这样的事情怎么样:
- (BOOL)isSameDayWithDate1:(NSDate*)date1 date2:(NSDate*)date2 {
NSCalendar* calendar = [NSCalendar currentCalendar];
unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
NSDateComponents* comp1 = [calendar components:unitFlags fromDate:date1];
NSDateComponents* comp2 = [calendar components:unitFlags fromDate:date2];
return [comp1 day] == [comp2 day] &&
[comp1 month] == [comp2 month] &&
[comp1 year] == [comp2 year];
}
回答by Joe Masilotti
If you are working with iOS 8 you can use -isDate:inSameDayAsDate:
.
如果您使用的是 iOS 8,则可以使用-isDate:inSameDayAsDate:
.
From NSCalendar.h
:
来自NSCalendar.h
:
/*
This API compares the Days of the given dates, reporting them equal if they are in the same Day.
*/
- (BOOL)isDate:(NSDate *)date1 inSameDayAsDate:(NSDate *)date2 NS_AVAILABLE(10_9, 8_0);
Note that for some reason this didn't make it to the official documentation on Apple's developer site. But it is definitely part of the public API.
请注意,由于某种原因,这并没有出现在 Apple 开发者网站上的官方文档中。但它绝对是公共 API 的一部分。
回答by Ben Lachman
(Note: Look at Joe's answer for a good way to do this on iOS 8+)
(注意:查看 Joe 的答案,了解在 iOS 8+ 上执行此操作的好方法)
I just use a date formatter:
我只使用日期格式化程序:
NSDateFormatter *dateComparisonFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateComparisonFormatter setDateFormat:@"yyyy-MM-dd"];
if( [[dateComparisonFormatter stringFromDate:firstDate] isEqualToString:[dateComparisonFormatter stringFromDate:secondDate]] ) {
…
}
HTH.
哈。
回答by vikzilla
In Swift:
在斯威夫特:
NSCalendar.currentCalendar().isDate(yourDate, equalToDate: yourOtherDate, toUnitGranularity: .Day)
It will return true if they are on the same day.
如果它们在同一天,它将返回 true。
回答by aapierce
I like progrmr's solution, but I would go even further and make a category of NSDate
that provides this method. It will make your code slightly more readable, and you won't need to copy and paste the method into each new class that might need it – just import the header file.
我喜欢 progrmr 的解决方案,但我会更进一步,创建一个NSDate
提供这种方法的类别。这将使您的代码更具可读性,并且您无需将该方法复制并粘贴到每个可能需要它的新类中——只需导入头文件即可。
NSDate+SameDay.h
NSDate+SameDay.h
@interface NSDate (SameDay)
- (BOOL)isSameDayAsDate:(NSDate*)otherDate;
@end
NSDate+SameDay.m
NSDate+SameDay.m
#import "NSDate+SameDay.h"
@implementation NSDate (SameDay)
- (BOOL)isSameDayAsDate:(NSDate*)otherDate {
// From progrmr's answer...
NSCalendar* calendar = [NSCalendar currentCalendar];
unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
NSDateComponents* comp1 = [calendar components:unitFlags fromDate:self];
NSDateComponents* comp2 = [calendar components:unitFlags fromDate:otherDate];
return [comp1 day] == [comp2 day] &&
[comp1 month] == [comp2 month] &&
[comp1 year] == [comp2 year];
}
@end
Then, after importing NSDate+SameDay.h
in your class, you can use it like so:
然后,NSDate+SameDay.h
在您的类中导入后,您可以像这样使用它:
if ([myFirstDate isSameDayAsDate:mySecondDate]) {
// The two dates are on the same day...
}
回答by Bruce Geerdes
I use NSDateComponents to strip out the time aspect and then compare. Something like:
我使用 NSDateComponents 去除时间方面然后进行比较。就像是:
if ([[self beginningOfDay:date1] isEqualToDate:[self beginningOfDay:date2]])
{
...
}
- (NSDate *)beginningOfDay:(NSDate *)date {
NSCalendar *calendar = [NSCalendar currentCalendar];
unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
NSDateComponents *comp = [calendar components:unitFlags fromDate:date];
return [calendar dateFromComponents:comp];
}
回答by philipp
NSCalendar.currentCalendar().isDateInToday(yourNSDate)
Available in iOS 8.0 and later and OS X v10.9 and later.
适用于 iOS 8.0 及更高版本和 OS X v10.9 及更高版本。
回答by norbDEV
in Swift 3.0, iOS8+
在 Swift 3.0, iOS8+
if NSCalendar.current.isDate(Date(), equalTo: date, toGranularity: .day) {
}
or
或者
if NSCalendar.current.isDateInToday(date) {
}
回答by vikingosegundo
Is there an easier/better way to do it than getting the NSDateComponents and comparing day/month/year?
有没有比获取 NSDateComponents 和比较日/月/年更简单/更好的方法?
Yes, there is an easier way
是的,有一个更简单的方法
-[NSCalendar rangeForUnit:startDate:interval:forDate:]
This methods makes it easy to set a date to a beginning of a unit (day, hour, month, year,…) and get the length (interval) of that unit.
-[NSCalendar rangeForUnit:startDate:interval:forDate:]
此方法可以轻松地将日期设置为单位(日、小时、月、年……)的开头并获取该单位的长度(间隔)。
As a category it might be used like
作为一个类别,它可以像
@interface NSDate (Comparison)
-(BOOL) isSameDay:(NSDate *)rhs;
@end
@implementation NSDate (Comparison)
-(BOOL)isSameDay:(NSDate *)rhs
{
NSDate *lhs = self;
NSDate *lhsStart;
NSDate *rhsStart;
NSCalendar *cal = [NSCalendar currentCalendar];
[cal rangeOfUnit:NSCalendarUnitDay startDate:&lhsStart interval:NULL forDate:lhs];
[cal rangeOfUnit:NSCalendarUnitDay startDate:&rhsStart interval:NULL forDate:rhs];
return [lhsStart compare:rhsStart] == NSOrderedSame;
}
@end
This category should work for all iOS versions and Mac OS X 10.5+.
此类别适用于所有 iOS 版本和 Mac OS X 10.5+。
for iOS 8+ and Mac OS X 10.9+, you can use NSCalendars
对于 iOS 8+ 和 Mac OS X 10.9+,您可以使用 NSCalendars
- (BOOL)isDate:(NSDate *)date1 equalToDate:(NSDate *)date2 toUnitGranularity:(NSCalendarUnit)unit;