IOS 日期对比

作者: 蜗牛1992 | 来源:发表于2017-11-02 17:10 被阅读2540次
#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];
        return date;
}
//日期对比
- (int)compareOneDay:(NSDate *)currentDay withAnotherDay:(NSDate *)BaseDay
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"dd-MM-yyyy-HHmmss"];
    NSString *currentDayStr = [dateFormatter stringFromDate:currentDay];
    NSString *BaseDayStr = [dateFormatter stringFromDate:BaseDay];
    NSDate *dateA = [dateFormatter dateFromString:currentDayStr];
    NSDate *dateB = [dateFormatter dateFromString:BaseDayStr];
    NSComparisonResult result = [dateA compare:dateB];
    NSLog(@"date1 : %@, date2 : %@", currentDay, BaseDay);
    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;
}

//使用
    NSDate *currentDay = [self getCurrentTime];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"dd-MM-yyyy-HHmmss"];
    NSDate *FinalDay = [dateFormatter dateFromString:@"31-12-2017-000000"];
    int isOn = [self compareOneDay:currentDay withAnotherDay:FinalDay];
    if (isOn == -1) {
        NSLog(@"在日期之前");
    }
    if (isOn == 1) {
        NSLog(@"在日期之后");
    }
    if (isOn == 0) {
        NSLog(@"在日期当天");
    }

相关文章

网友评论

    本文标题:IOS 日期对比

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