在项目中日期的显示常常会当天的显示时分,当月的显示日时和分,以此类推,不免会涉及到日期的比较,下面介绍一下日期比较的两种方法spa
比较日期有两种方法code
一种是经过系统的NSCalendar类实现component
NSString * date = @"2016-10-12 13:12:12";orm
//建立日期格式blog
NSDateFormatter * dateFormat = [[NSDateFormatter alloc]init];字符串
[dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];it
[dateFormat setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];io
//字符串转为日期class
NSDate *showDate =[dateFormat dateFromString:date];date
//建立日历类
NSCalendar * calendar = [NSCalendar currentCalendar];
//比较如今的时间和
NSDateComponents * components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:showDate toDate:[NSDate date] options:NSCalendarWrapComponents];
if (components.year) {
NSLog(@"同一年");
}else{
if (components.month) {
NSLog(@"同一月");
}else{
NSLog(@"不一样月");
}
}
另外一种方法是:
利用时间的实例方法timeIntervalSinceDate:就会得出两个时间相差的秒数,再计算相差的天数
NSString * date = @"2016-10-13 9:04:00"; //建立日期格式 NSDateFormatter * dateFormat = [[NSDateFormatter alloc]init]; [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; [dateFormat setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]]; //字符串转为日期 NSDate *showDate =[dateFormat dateFromString:date]; NSDate * nowDate = [NSDate date]; NSTimeInterval timeInterval = [nowDate timeIntervalSinceDate:showDate]; NSLog(@"分差=%f",timeInterval/60.00);//分差 NSLog(@"时差=%f",timeInterval/3600.00);//时差 NSLog(@"天数差=%f",timeInterval/3600.00/24);//天数差,若是是0说明是当天,不然不是当天