IOS 日期判断 今天、昨天、以前

这个不难,只是记录下,方便自己和有需要的同学。

// 注意传入的 today 和 otherDay的时间格式为: yyyy-MM-dd hh:mm:ss 例子 2014-04-24 11:09:06
- (int)compareDate:(NSString*)today withDate:(NSString*)otherDay{
    int ci;
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    today = [[today componentsSeparatedByString:@" "] objectAtIndex:0];
    otherDay = [[otherDay componentsSeparatedByString:@" "] objectAtIndex:0];
    [df setDateFormat:@"yyyy-MM-dd"];
    NSDate *dt1 = [[NSDate alloc] init];
    NSDate *dt2 = [[NSDate alloc] init];
    dt1 = [df dateFromString:today];
    dt2 = [df dateFromString:otherDay];
    [NSDate  timeIntervalSinceReferenceDate];
    NSComparisonResult result = [dt1 compare:dt2];
    switch (result)
    {
            //today比otherDay大
        case NSOrderedDescending: {
            NSTimeInterval dayTime = 24*60*60;
            // 将today往前减少一天的时间,判断是否和昨天的时间是否相等,如果相等则表示
            // otherDay为昨天
            NSDate * newDate = [dt1 dateByAddingTimeInterval:-dayTime];
            result = [dt2 compare:newDate];
            if (result == NSOrderedSame) {
                // 表示日期为昨天
                ci = -1;
            } else {
                // 表示日期为昨天以前的时间
                ci = 1;
            }
        }
            break;
            //date02=date01,代表日期是今天
        case NSOrderedSame: ci=0;
            break;
        default:
            // 默认显示所有的具体的日期时间
            ci = 1;
            break;
    }
    return ci;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值