if (datStartDate > datEndDate) {
This doesn't seem t开发者_运维百科o work. I know there's a isEqual
, etc., but how do I perform "is greater than"?
There are both NSDate
.
The easiest method i'm aware is:
if( [firstDate timeIntervalSinceDate:secondDate] > 0 ) {
The other answers cover compare:, wanted to add some flavour ;).
To compare dates use -compare:
method:
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.
What about...
if ([datStartDate earlierDate: datEndDate] == datStartDate) {
// datStartDate is earlier
} else {
// datEndDate is earlier
}
As you have NSDates:
NSDate *datStartDate = [NSDate dateWithString:@"2010-10-01 03:00:00 +0900"];
NSDate *datEndDate = [NSDate dateWithString:@"2010-10-01 04:00:00 +0900"];
if ( ([datStartDate compare:datEndDate]) == NSOrderedDescending ) {
...
}
Swift 2 version of accepted answer:
if firstDate.timeIntervalSinceDate(secondDate) > 0 {
// firstDate is greater (further in the future) than secondDate
}
I've been working with NSDate and NSComparison result stuff for years and I can never for the life of me remember how this works. So I wrote a convenience extension on Date
for it:
func isBefore(_ otherDate: Date) -> Bool {
let result = self.compare(otherDate)
switch result {
case .orderedAscending:
return true
case .orderedSame,
.orderedDescending:
return false
}
}
If you want to have an isAfter
extension it just has to return true
for orderedDescending
.
if ([startDate compare:endDate] == NSOrderedAscending) {
NSLog(@"startDate is EARLIER than endDate");
}
精彩评论