iOS比较当前日期与指定日期大小
Posted 我就是一种相逢
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了iOS比较当前日期与指定日期大小相关的知识,希望对你有一定的参考价值。
#pragma mark -得到当前时间 - (NSDate *)getCurrentTime{ NSDateFormatter *formatter=[[NSDateFormatter alloc]init]; [formatter setDateFormat:@"dd-MM-yyyy-HHmmss"]; NSString *dateTime=[formatter stringFromDate:[NSDate date]]; NSDate *date = [formatter dateFromString:dateTime]; NSLog(@"---------- currentDate == %@",date); return date; }
将指定日期(此处以2016-09-30-00点为例)转换为同样日期格式,返回NSDate形式
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"dd-MM-yyyy-HHmmss"]; NSDate *date = [dateFormatter dateFromString:@"30-09-2016-000000"];
将现在的时间与指定时间比较,如果没达到指定日期,返回-1,刚好是这一时间,返回0,否则返回1
- (int)compareOneDay:(NSDate *)oneDay withAnotherDay:(NSDate *)anotherDay { NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"dd-MM-yyyy-HHmmss"]; 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(@"date1 : %@, date2 : %@", oneDay, anotherDay); if (result == NSOrderedDescending) { //NSLog(@"Date1 is in the future"); return 1; } else if (result == NSOrderedAscending){ //NSLog(@"Date1 is in the past"); return -1; } //NSLog(@"Both dates are the same"); return 0; }
使用
以上是关于iOS比较当前日期与指定日期大小的主要内容,如果未能解决你的问题,请参考以下文章