iOS时间显示今天昨天
一、前言
今天无意间想起写这个功能,仔细考虑了一下,其实很简单,整体思路如下:
先获取你所要转换的时间的年月日,然后再获取今天和昨天的年月日,然后对比,进而返回不同的字符串。
二、实现步骤
首先,我们设置一下时间格式:
NSDateFormatter *format = [[NSDateFormatter alloc] init]; [format setDateFormat:@"YYYY年MM月dd日"];
NSDateFormatter *fo = [[NSDateFormatter alloc] init];
[fo setDateFormat:@"HH:mm"];
然后我们要获得传过来的时间的年月日和时分:
//获取传过来的时间的时分 NSString *hoursandSec = [fo stringFromDate:date]; //获取传过来的时间的date NSString *createDate = [format stringFromDate:date];
然后获取今天和昨天的年月日:
//获取今天 NSDate *nowDate = [NSDate date]; NSString *today = [format stringFromDate:nowDate]; //获取昨天 NSDate *yesterdayDate = [NSDate dateWithTimeIntervalSinceNow:-(24*60*60)]; NSString *yesterday = [format stringFromDate:yesterdayDate];
然后对比返回数据即可:
if ([createDate isEqualToString:today]) { return [NSString stringWithFormat:@"今天%@",hoursandSec]; }else if ([createDate isEqualToString:yesterday]) { return [NSString stringWithFormat:@"昨天%@",hoursandSec]; }else { return [NSString stringWithFormat:@"%@ %@",createDate,hoursandSec]; }
完成。
三、附加方法源码
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
/获取时间:今天昨天 +(NSString *)getYMD:(NSDate *)date { NSDateFormatter *format = [[NSDateFormatter alloc] init]; [format setDateFormat:@"YYYY年MM月dd日"]; //获取传过来的时间的时分 NSDateFormatter *fo = [[NSDateFormatter alloc] init]; [fo setDateFormat:@"HH:mm"]; NSString *hoursandSec = [fo stringFromDate:date]; //获取传过来的时间的date NSString *createDate = [format stringFromDate:date]; //获取今天 NSDate *nowDate = [NSDate date]; NSString *today = [format stringFromDate:nowDate]; //获取昨天 NSDate *yesterdayDate = [NSDate dateWithTimeIntervalSinceNow:-(24*60*60)]; NSString *yesterday = [format stringFromDate:yesterdayDate]; if ([createDate isEqualToString:today]) { return [NSString stringWithFormat:@"今天%@",hoursandSec]; }else if ([createDate isEqualToString:yesterday]) { return [NSString stringWithFormat:@"昨天%@",hoursandSec]; }else { return [NSString stringWithFormat:@"%@ %@",createDate,hoursandSec]; } }