我有三个日期:(1)previousDate(2)currentDate(3)nextDate, 我想检查currentDate是否晚于上一个日期,早于nextDate。 我该怎么做?
答案 0 :(得分:7)
NSDateFormatter *df= [[NSDateFormatter alloc] init];
[df setDateFormat:@"yyyy-MM-dd"];
NSDate *dt1 = [[NSDate alloc] init];
NSDate *dt2 = [[NSDate alloc] init];
dt1=[df dateFromString:@"2011-02-25"];
dt2=[df dateFromString:@"2011-03-25"];
NSComparisonResult result = [dt1 compare:dt2];
switch (result)
{
case NSOrderedAscending: NSLog(@"%@ is greater than %@", dt2, dt1); break;
case NSOrderedDescending: NSLog(@"%@ is less %@", dt2, dt1); break;
case NSOrderedSame: NSLog(@"%@ is equal to %@", dt2, dt1); break;
default: NSLog(@"erorr dates %@, %@", dt2, dt1); break;
}
答案 1 :(得分:6)
我想你正在使用NSDate类。
您可以使用isEqualToDate来比较两个NSDate对象。另外,检查currentdate的earlierDate和laterDate比上一个日期更大,小于下一个日期。
答案 2 :(得分:4)
我只是用它来检查它:
if ([[currentDate laterDate:nextDate] isEqualToDate:nextDate]) {
NSLog(@"currentDate is earlier than nextDate");
}
if ([[currentDate laterDate:previousDate] isEqualToDate:currentDate]) {
NSLog(@"currentDate is later then previousDate");
}
对我来说很好!感谢@Luca Matteis提示“laterDate:”
答案 3 :(得分:2)
我们可以在Swift 5.0中轻松比较两个日期
switch dateOld.compare(dateNew) {
case .orderedAscending:
// Put your code for greater
break
case .orderedDescending:
// Put your code less
break;
case .orderedSame:
// Put your code for equal
break
}
答案 4 :(得分:0)
NSDate对象还实现了记录良好的-compare:method。
答案 5 :(得分:0)
只需使用compare
的{{1}}消息执行两次比较:
NSDate