美文网首页
iOS中比较当前日期与指定日期大小

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

作者: ShineYangGod | 来源:发表于2017-09-01 15:03 被阅读28次

    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;

    }
    //调用
    [self compareOneDay:[self getCurrentTime] withAnotherDay:date]

    相关文章

      网友评论

          本文标题:iOS中比较当前日期与指定日期大小

          本文链接:https://www.haomeiwen.com/subject/izfkjxtx.html