一、日期和时间模式
日期和时间格式由日期和时间模式字符串组成,在日期和时间模式字符串中未加引号的'A'到‘Z’和'a'到‘z’被解释为模式字母,用来表示日期或时间。 字符串元素,文本可以使用单引号(‘’)引起来使用。 定义以下模式字母(所有其他字符‘A’到‘Z’,'a'到‘z’都被保留)
二、日期格式化
1、 yyyy-MM-dd HH:mm:ss 2014-12-12 12:12:12 2、 yyyy/MM/dd HH:mm:ss 2014/12/12 12:12:12
三、思维导图
四、事例代码
xzr_formatter 是自定义的静态formatter类 //是今年 - (BOOL)xzr_isToYear{ NSCalendar *calendar = [NSCalendar xzr_calendar]; NSCalendarUnit unit = NSCalendarUnitYear; NSDateComponents *selfComponents = [calendar components:unit fromDate:计算的日期]; NSDateComponents *nowComponents = [calendar components:unit fromDate:[NSDate date]]; //年都一样 return (selfComponents.year == nowComponents.year); } //是今天 - (BOOL)xzr_isToday{ NSCalendar *calendar = [NSCalendar xzr_calendar]; // 自定义方法获取日历类对象 NSCalendarUnit unit = NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay; //计算的日期,如年,月,日 NSDateComponents *selfComponents = [calendar components:unit fromDate:计算的日期]; NSDateComponents *nowComponents = [calendar components:unit fromDate:[NSDate date]];//现在日期 return (selfComponents.year == nowComponents.year && selfComponents.month == nowComponents.month && selfComponents.day == nowComponents.day); } //判断日期处理 + (NSString *)xzr_dateString:(NSString *)string{ //日期格式 xzr_formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss"; NSDate *createDate = [xzr_formatter dateFromString:string] ; if (createDate.xzr_isToYear) {//是今年 if (createDate.xzr_isToday) {//今天 NSDate *nowDate = [NSDate date]; NSCalendarUnit unit = NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond; NSDateComponents *components = [xzr_calendar components:unit fromDate:createDate toDate:nowDate options:NSCalendarWrapComponents ]; if (components.hour >= 1) {//几小时前 return [NSString stringWithFormat:@"%ld小时前",components.hour]; }else if (components.minute >=1){//几分钟前 return [NSString stringWithFormat:@"%ld分钟前",components.minute]; }else{//刚刚 return @"刚刚"; } }else if (createDate.xzr_isToYestoday){//昨天 xzr_formatter.dateFormat = @"昨天 HH:mm:ss"; return [xzr_formatter stringFromDate:createDate]; }else{ xzr_formatter.dateFormat = @"MM-dd HH:mm:ss"; return [xzr_formatter stringFromDate:createDate]; } }else{ return string; } }