最新下载
热门教程
- 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
相关文章
- 王者荣耀侦探能力大测试攻略 王者荣耀侦探能力大测试怎么过 11-22
- 无期迷途主线前瞻兑换码是什么 11-22
- 原神欧洛伦怎么培养 11-22
- 炉石传说网易云音乐联动怎么玩 11-22
- 永劫无间手游确幸转盘怎么样 11-22
- 无期迷途主线前瞻兑换码是什么 无期迷途主线前瞻直播兑换码介绍 11-22