iOS日期处理

//转换创建时间的格式
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    fmt.dateFormat = @"EEE MMM dd HH:mm:ss Z yyyy";
    fmt.locale = [NSLocale localeWithLocaleIdentifier:@"en_US"];
    NSDate *createdDate = [fmt dateFromString:_created_at];
    //NSDate *createdDate = [fmt dateFromString:@"Thu May 19 13:20:20 +0800 2014"];
    fmt.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    NSString *createdStr = [fmt stringFromDate:createdDate];
    createdDate = [fmt dateFromString:createdStr];



    NSDate *now = [NSDate date];//2015-05-22 14:16:16 +0000
    NSCalendar *calender = [NSCalendar currentCalendar];
    //why?
    NSDateComponents *compareComponents = [calender components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay |NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond ) fromDate:createdDate toDate:now options:0]; //!!!!!!!

    //NSLog(@"%@",compareComponents);

    NSDateComponents *createdComponents = [calender components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay ) fromDate:createdDate];
    NSDateComponents *nowComponents = [calender components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay ) fromDate:now];



    BOOL isThisYear = createdComponents.year == nowComponents.year;
    BOOL isToday = createdComponents.month == nowComponents.month && createdComponents.day == nowComponents.day;
    BOOL isYesterday = createdComponents.month == nowComponents.month && compareComponents.day == 1;

    if (isThisYear) { //今年

        if (isToday) {//今天

            if (fabs([now timeIntervalSinceDate:createdDate]) < 60) {//小于一分钟
                return @"刚刚";
            } else if (compareComponents.hour == 0) { //小于一个小时
                return [NSString stringWithFormat:@"%ld分钟前",compareComponents.minute];
            } else { //大于一个小时
                return [NSString stringWithFormat:@"%ld小时前",compareComponents.hour];
            }
        } else if (isYesterday) { //昨天
            fmt.dateFormat = @"HH:mm:ss";
            NSString *str = [fmt stringFromDate:createdDate];
            return [NSString stringWithFormat:@"昨天 %@",str];
        } else { //今年的其他日子
            fmt.dateFormat = @"MM-dd HH:mm:ss";
            return [fmt stringFromDate:createdDate];
        }
    } else {//其他年份
        return [fmt stringFromDate:createdDate];
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值