[英]How to compare two date?
我有三个日期:(1)previousDate(2)currentDate(3)nextDate,我想检查currentDate是否晚于上一个日期,早于nextDate。 我怎么做?
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;
}
我想你正在使用NSDate类。
您可以使用isEqualToDate来比较两个NSDate对象。 而且,检查currentdate的earlyDate和laterDate比前一个日期更大,并且小于下一个日期。
我只是用它来检查它:
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:”
我们可以在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
}
NSDate对象还实现了记录良好的-compare:方法。
只需使用NSDate
的compare
消息执行两次比较:
if ([previousDate compare:currentDate] == NSOrderedAscending &&
[nextDate compare:currentDate] == NSOrderedDescending) {
NSLog(@"current date is in between previous and next date (non-inclusive)");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.