iOS判断日期A是否在日期B到日期C之间

本文详细介绍了三种使用Objective-C比较日期的方法:直接使用时间戳比较、使用NSCalendar进行日期比较以及自定义方法比较日期区间。

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

方法一: 可以用nsdate 的 timeIntervalSince1970 方法把时间转换成时间戳进行比较,这里timeIntervalSince1970返回的是NSTimeInterval(double)类型,直接比较就可以了

方法二:使用nsdate的compare方法实现

- (BOOL)date:(NSDate*)date isBetweenDate:(NSDate*)beginDate andDate:(NSDate*)endDate
{
    if ([date compare:beginDate] == NSOrderedAscending)
        return NO;
    
    if ([date compare:endDate] == NSOrderedDescending)
        return NO;
    
    return YES;
}

方法三:

NSCalendar *calendar= [NSCalendar currentCalendar];
NSInteger desiredComponents= (NSDayCalendarUnit | NSMonthCalendarUnit);
NSDateComponents *firstComponents= [calendar components:desiredComponents fromDate:Date1];
NSDateComponents *secondComponents= [calendar components:desiredComponents fromDate:Date2];
NSDate *firstWOYear= [calendar dateFromComponents:firstComponents];
NSDate *SecondWOYear = [calendar dateFromComponents:secondComponents];
NSComparisonResult result= [firstWOYear compare:SecondWOYear];
if (result== NSOrderedAscending) {  

} else if (result== NSOrderedDescending) { 

}  else {  

}

  

转载于:https://www.cnblogs.com/cocoajin/p/3152929.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值