iOS NSComparisonResult:将当前时间与指定时间进行对比

1.首先获取当前时间的字符串

+ (NSString *)getCurrentTime{
    NSDateFormatter *formatter=[[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    [formatter setTimeZone:timeZone];
    NSString *dateTime=[formatter stringFromDate:[NSDate date]];

    return dateTime;
}

2.将指定的时间戳按相同的格式(例如:yyyy-MM-dd HH:mm:ss),转化为字符串
3.将当前时间oneDay与指定时间anotherDay进行对比
①如果result == NSOrderedDescending,说明当前时间大于指定时间
②如果result == NSOrderedAscending,说明当前时间小于指定时间
③如果以上两种都不是,说明当前时间与指定时间相同

+ (int)compareOneDay:(NSString *)oneDay withAnotherDay:(NSString *)anotherDay
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *dateA = [dateFormatter dateFromString:oneDay];
    NSDate *dateB = [dateFormatter dateFromString:anotherDay];
    NSComparisonResult result = [dateA compare:dateB];
    if (result == NSOrderedDescending) {
        //NSLog(@"DateA  is in the future");
        return 1;
    }
    else if (result == NSOrderedAscending){
        //NSLog(@"DateA is in the past");
        return -1;
    }else{
    //NSLog(@"Both dates are the same");
    return 0;
}
    
}

你可能感兴趣的:(iOS NSComparisonResult:将当前时间与指定时间进行对比)