1. 程式人生 > >當前日期與制定日期的比較

當前日期與制定日期的比較

1、首先獲取當前日期NSDate形式,指定一個日期格式

#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; }

2、然後將指定日期(此處以2016-09-30-00點為例)轉換為同樣日期格式,返回NSDate形式

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];  
   [dateFormatter setDateFormat:@"dd-MM-yyyy-HHmmss"];  
   NSDate *date = [dateFormatter dateFromString:@"30-09-2016-000000"]; 

3、最後進行比較,將現在的時間與指定時間比較,如果沒達到指定日期,返回-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; }

4、比較

[self compareOneDay:[self getCurrentTime] withAnotherDay:date];