码迷,mamicode.com
首页 > 其他好文 > 详细

NSDate+Category 将日期输出为今天 09:00 or 昨天 09:00

时间:2015-12-31 12:25:12      阅读:115      评论:0      收藏:0      [点我收藏+]

标签:

1. 创建一个NSDate 的类别

.h 方法

-(NSString *)dateAmity;

 

.m方法实现

 

-(NSString *)dateAmity

{

    BOOL isThisYear=false,isThisMonth=false,isThisDay=false,isYesterDay=false,isTomorrow=false;

    

    NSString *str = @"";

    

    NSDate *now = [NSDate date];

    

    NSDateComponents *nowComs = [[NSCalendar currentCalendar] components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:now];

    NSDateComponents *selfComs = [[NSCalendar currentCalendar] components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:self];

    

    if (nowComs.year == selfComs.year) {

        isThisYear = true;

    }

    

    if (nowComs.month == selfComs.month && isThisYear) {

        isThisMonth = true;

    }

    

    if (nowComs.day == selfComs.day && isThisMonth) {

        isThisDay = true;

    }else if (nowComs.day == selfComs.day+1 && isThisMonth){

        isYesterDay = true;

    }else if (nowComs.day == selfComs.day-1 && isThisMonth){

        isTomorrow = true;

    }

    

    NSDateFormatter *dateFormate = [NSDateFormatter new];

    dateFormate.dateFormat = @"yyyy/MM/dd HH:mm";

    

    NSString *header = @"";

    

    if (isThisYear) {

        dateFormate.dateFormat = @"MM/dd HH:mm";

        

        if (isThisDay) {

//            header = @"今天 ";

            header = @" ";

        }else if (isYesterDay) {

            header = @"昨天 ";

        }else if (isTomorrow) {

            header = @"明天 ";

        }

        if (![header isEqualToString:@""]) {

            dateFormate.dateFormat = @"HH:mm";

        }

    }

    

    str = [NSString stringWithFormat:@"%@%@",header,[dateFormate stringFromDate:self]];

    

    return str;

}

NSDate+Category 将日期输出为今天 09:00 or 昨天 09:00

标签:

原文地址:http://www.cnblogs.com/heiheihei/p/5090891.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!