码迷,mamicode.com
首页 > 移动开发 > 详细

iOS比较当前日期与指定日期大小

时间:2017-08-22 11:42:34      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:future   formatter   des   pre   当前日期   datetime   att   das   color   

    #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比较当前日期与指定日期大小

标签:future   formatter   des   pre   当前日期   datetime   att   das   color   

原文地址:http://www.cnblogs.com/ios988/p/7410758.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!