最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
iOS 时间(年月日)大小的比较的例子
时间:2022-06-25 23:34:46 编辑:袖梨 来源:一聚教程网
一般说到比较大小,我们都会想到比较两个数字的大小,但是如果让你比较两个日期的大小呢,如:比较2016-07-21和2016-08-20的大小,NSDate之间的比较有compare来实现,整理方法,代码如下:
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
NSDate *date1 = [dateFormatter dateFromString:@"2016-07-21"];
NSDate *date2 = [dateFormatter dateFromString:@"2016-08-20"];
if ([[NSString stringWithFormat:@"%d",[self compareOneDay:date1 withAnotherDay:date2]] isEqualToString:@"1"]) {
NSLog(@"date1 > date2");
}else if ([[NSString stringWithFormat:@"%d",[self compareOneDay:date1 withAnotherDay:date2]] isEqualToString:@"-1"]){
NSLog(@"date1 < date2");
}else{
NSLog(@"date1 = date2");
}
}
#pragma mark - 时间比较大小
- (int)compareOneDay:(NSDate *)oneDay withAnotherDay:(NSDate *)anotherDay
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd-MM-yyyy"];
NSString *oneDayStr = [dateFormatter stringFromDate:oneDay];
NSString *anotherDayStr = [dateFormatter stringFromDate:anotherDay];
NSDate *dateA = [dateFormatter dateFromString:oneDayStr];
NSDate *dateB = [dateFormatter dateFromString:anotherDayStr];
NSComparisonResult result = [dateA compare:dateB];
NSLog(@"oneDay : %@, anotherDay : %@", oneDay, anotherDay);
if (result == NSOrderedDescending) {
//oneDay > anotherDay
return 1;
}
else if (result == NSOrderedAscending){
//oneDay < anotherDay
return -1;
}
//oneDay = anotherDay
return 0;
}
打印:
2016-08-20 09:41:04.061 CompareDateTime[16742:676557] date1 : 2016-07-20 16:00:00 +0000, date2 : 2016-08-19 16:00:00 +0000
2016-08-20 09:41:04.062 CompareDateTime[16742:676557] date1 < date2
相关文章
- 以闪亮之名店长体验流霞季怎么玩 缘溪临霞套装活动介绍 12-31
- 未定事件簿旧梦新生左然篇怎么玩 旧梦新生左然篇活动介绍 12-31
- 未定事件簿左然破浪远行怎么样 12-31
- 桃源深处有人家行医问诊怎么玩 12-31
- 恋与制作人跨年福利有哪些 恋与制作人跨年福利内容介绍 12-31
- 阴阳师协同对弈大乱斗怎么玩 阴阳师协同对弈大乱斗活动介绍 12-31