iOS:比较两个日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6112075/
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
iOS: Compare two dates
提问by cyclingIsBetter
I have a NSDate
that I must compare with other two NSDate
and I try with NSOrderAscending
and NSOrderDescending
but if my date is equal at other two dates?
我有一个NSDate
我必须与其他两个比较,NSDate
我尝试使用NSOrderAscending
,NSOrderDescending
但是如果我的日期在其他两个日期相等?
Example: if I have a myDate = 24/05/2011
and other two that are one = 24/05/2011
and two 24/05/2011
what can I use?
示例:如果我有一个myDate = 24/05/2011
和其他两个是一个 =24/05/2011
和两个,24/05/2011
我可以使用什么?
回答by Vincent Guerci
According to Apple documentation of NSDate compare:
Returns an NSComparisonResult value that indicates the temporal ordering of the receiver and another given date.
- (NSComparisonResult)compare:(NSDate *)anotherDate
Parameters
anotherDate
The date with which to compare the receiver. This value must not be nil. If the value is nil, the behavior is undefined and may change in future versions of Mac OS X.
Return Value
If:
The receiver and anotherDate are exactly equal to each other,
NSOrderedSame
The receiver is later in time than anotherDate,
NSOrderedDescending
The receiver is earlier in time than anotherDate,
NSOrderedAscending
返回一个 NSComparisonResult 值,该值指示接收者和另一个给定日期的时间顺序。
- (NSComparisonResult)compare:(NSDate *)anotherDate
参数
anotherDate
与接收方进行比较的日期。该值不能为零。如果值为 nil,则行为未定义,并且可能会在 Mac OS X 的未来版本中更改。
返回值
如果:
接收者和另一个日期完全相等,
NSOrderedSame
接收者的时间晚于另一个日期,
NSOrderedDescending
接收者在时间上早于另一个日期,
NSOrderedAscending
In other words:
换句话说:
if ([date1 compare:date2] == NSOrderedSame) ...
Note that it might be easier in your particular case to read and write this :
请注意,在您的特定情况下,阅读和编写此内容可能更容易:
if ([date2 isEqualToDate:date2]) ...
See Apple Documentation about this one.
请参阅有关此的 Apple 文档。
回答by Yossi Tsafar
After searching stackoverflow and the web a lot, I've got to conclution that the best way of doing it is like this:
在大量搜索 stackoverflow 和网络之后,我得出结论,最好的方法是这样的:
- (BOOL)isEndDateIsSmallerThanCurrent:(NSDate *)checkEndDate
{
NSDate* enddate = checkEndDate;
NSDate* currentdate = [NSDate date];
NSTimeInterval distanceBetweenDates = [enddate timeIntervalSinceDate:currentdate];
double secondsInMinute = 60;
NSInteger secondsBetweenDates = distanceBetweenDates / secondsInMinute;
if (secondsBetweenDates == 0)
return YES;
else if (secondsBetweenDates < 0)
return YES;
else
return NO;
}
You can change it to difference between hours also.
您也可以将其更改为小时之间的差异。
Enjoy!
享受!
Edit 1
编辑 1
If you want to compare date with format of dd/MM/yyyy only, you need to add below lines between NSDate* currentdate = [NSDate date];
&& NSTimeInterval distance
如果您只想将日期与 dd/MM/yyyy 格式进行比较,则需要在NSDate* currentdate = [NSDate date];
&&之间添加以下行NSTimeInterval distance
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd/MM/yyyy"];
[dateFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]
autorelease]];
NSString *stringDate = [dateFormatter stringFromDate:[NSDate date]];
currentdate = [dateFormatter dateFromString:stringDate];
回答by Himadri Choudhury
I take it you are asking what the return value is in the comparison function.
我认为您是在问比较函数中的返回值是什么。
If the dates are equal then returning NSOrderedSame
如果日期相等则返回 NSOrderedSame
If ascending ( 2nd arg > 1st arg ) return NSOrderedAscending
如果升序(第二个 arg > 1st arg)返回 NSOrderedAscending
If descending ( 2nd arg < 1st arg ) return NSOrderedDescending
如果降序(第二个 arg < 1st arg )返回 NSOrderedDescending
回答by Matthias Bauch
I don't know exactly if you have asked this but if you only want to compare the date component of a NSDate you have to use NSCalendar and NSDateComponents to remove the time component.
我不知道您是否已经问过这个问题,但如果您只想比较 NSDate 的日期组件,则必须使用 NSCalendar 和 NSDateComponents 来删除时间组件。
Something like this should work as a category for NSDate:
像这样的东西应该作为 NSDate 的一个类别:
- (NSComparisonResult)compareDateOnly:(NSDate *)otherDate {
NSUInteger dateFlags = NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit;
NSCalendar *gregorianCalendar = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDateComponents *selfComponents = [gregorianCalendar components:dateFlags fromDate:self];
NSDate *selfDateOnly = [gregorianCalendar dateFromComponents:selfComponents];
NSDateComponents *otherCompents = [gregorianCalendar components:dateFlags fromDate:otherDate];
NSDate *otherDateOnly = [gregorianCalendar dateFromComponents:otherCompents];
return [selfDateOnly compare:otherDateOnly];
}
回答by JeremyP
NSDate
actually represents a time interval in seconds since a reference date (1st Jan 2000 UTC I think). Internally, a double precision floating point number is used so two arbitrary dates are highly unlikely to compare equal even if they are on the same day. If you want to see if a particular date falls on a particular day, you probably need to use NSDateComponents
. e.g.
NSDate
实际上表示自参考日期(我认为 2000 年 1 月 1 日 UTC)以来的时间间隔(以秒为单位)。在内部,一个双精度浮点数使用,以便任意两个日期是极不可能相等时,即使他们是在同一天进行比较。如果您想查看特定日期是否属于特定日期,您可能需要使用NSDateComponents
. 例如
NSDateComponents* dateComponents = [[NSDateComponents alloc] init];
[dateComponents setYear: 2011];
[dateComponents setMonth: 5];
[dateComponents setDay: 24];
/*
* Construct two dates that bracket the day you are checking.
* Use the user's current calendar. I think this takes care of things like daylight saving time.
*/
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDate* startOfDate = [calendar dateFromComponents: dateComponents];
NSDateComponents* oneDay = [[NSDateComponents alloc] init];
[oneDay setDay: 1];
NSDate* endOfDate = [calendar dateByAddingComponents: oneDay toDate: startOfDate options: 0];
/*
* Compare the date with the start of the day and the end of the day.
*/
NSComparisonResult startCompare = [startOfDate compare: myDate];
NSComparisonResult endCompare = [endOfDate compare: myDate];
if (startCompare != NSOrderedDescending && endCompare == NSOrderedDescending)
{
// we are on the right date
}
回答by Akhtar
Check the following Function for date comparison first of all create two NSDate objects and pass to the function: Add the bellow lines of code in viewDidload or according to your scenario.
检查以下用于日期比较的函数首先创建两个 NSDate 对象并传递给该函数:在 viewDidload 中或根据您的场景添加以下代码行。
-(void)testDateComaparFunc{
NSString *getTokon_Time1 = @"2016-05-31 03:19:05 +0000";
NSString *getTokon_Time2 = @"2016-05-31 03:18:05 +0000";
NSDateFormatter *dateFormatter=[NSDateFormatter new];
[dateFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss Z"];
NSDate *tokonExpireDate1=[dateFormatter dateFromString:getTokon_Time1];
NSDate *tokonExpireDate2=[dateFormatter dateFromString:getTokon_Time2];
BOOL isTokonValid = [self dateComparision:tokonExpireDate1 andDate2:tokonExpireDate2];}
here is the function
这是功能
-(BOOL)dateComparision:(NSDate*)date1 andDate2:(NSDate*)date2{
BOOL isTokonValid;
if ([date1 compare:date2] == NSOrderedDescending) {
//"date1 is later than date2
isTokonValid = YES;
} else if ([date1 compare:date2] == NSOrderedAscending) {
//date1 is earlier than date2
isTokonValid = NO;
} else {
//dates are the same
isTokonValid = NO;
}
return isTokonValid;}
Simply change the date and test above function :)
只需更改日期并测试上述功能:)