iOS的(NSDate)时间大小比较

本文介绍了两种在iOS中比较NSDate时间的方案:一是利用NSDate自带的系统方法;二是通过封装- (NSComparisonResult)compare:(NSDate *)other,需要注意的是,此方法默认比较年月日,若需考虑时分秒,需调整dateFormatter格式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

方法一、NSDate自带的系统方法

日期之间比较可用以下方法
    - (BOOL)isEqualToDate:(NSDate *)otherDate;
    与otherDate比较,相同返回YES
 
    - (NSDate *)earlierDate:(NSDate *)anotherDate;
    与anotherDate比较,返回较早的那个日期
 
    - (NSDate *)laterDate:(NSDate *)anotherDate;
    与anotherDate比较,返回较晚的那个日期
 
    - (NSComparisonResult)compare:(NSDate *)other;
 
    该方法用于排序时调用:
      . 当实例保存的日期值与anotherDate相同时返回NSOrderedSame
      . 当实例保存的日期值晚于anotherDate时返回NSOrderedDescending
      . 当实例保存的日期值早于anotherDate时返回NSOrderedAscending

方法二、对其中的 - (NSComparisonResult)compare:(NSDate *)other;进行封装

+(int)compareOneDay:(NSDate *)oneDay withAnotherDay:(NSDate *)anotherDay
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
 
    [dateFormatter setDateFormat:@"dd-MM-yyyy"];
 
    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];
 
    if (result == NSOrderedDescending) {
        //NSLog(@"oneDay比 anotherDay时间晚");
        return 1;
    }
    else if (result == NSOrderedAscending){
        //NSLog(@"oneDay比 anotherDay时间早");
        return -1;
    }
    //NSLog(@"两者时间是同一个时间");
    return 0;
}

方法二使用注意事项:首先,方法二的方法是一个类方法,我一般会把它写在NSDate的延展当中,或者把它写成一个对象方法,在对应的类中,使用self调用.其实,第二个方法是对年月日这三级进行比较,时分秒并没有添加进来如果需要的需要修改dateFormatter的@"dd-MM-yyyy"格式改成你想要比较的级数.
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值