iOS實現(xiàn)時間顯示幾分鐘前,幾小時前以及剛剛的方法示例
前言
本文實現(xiàn)的效果類似于QQ空間里的好友發(fā)表的動態(tài),會顯示好友發(fā)表的時間,這里是處理顯示幾小時前,幾分鐘前,剛剛,昨天,前天這樣的格式,下面來一起看看吧。
一:剛剛,幾分鐘前,幾小時前
//時間
NSString *createdTimeStr = @"2017-01-01 21:05:10";
//把字符串轉為NSdate
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *timeDate = [dateFormatter dateFromString:createdTimeStr];
//得到與當前時間差
NSTimeInterval timeInterval = [timeDate timeIntervalSinceNow];
timeInterval = -timeInterval;
long temp = 0;
NSString *result;
if (timeInterval < 60) {
result = [NSString stringWithFormat:@"剛剛"];
}else if((temp = timeInterval/60) < 60){
result = [NSString stringWithFormat:@"%ld分鐘前",temp];
}else if((temp = timeInterval/3600) > 1 && (temp = timeInterval/3600) <24){
result = [NSString stringWithFormat:@"%ld小時前",temp];
}else{
result = createdTimeStr;
}
NSLog(@"%@",result);
二:剛剛,幾分鐘前,幾小時前,昨天,前天
//時間
NSString *createdTimeStr = @"2017-01-01 21:05:10";
//把字符串轉為NSdate
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *timeDate = [dateFormatter dateFromString:createdTimeStr];
//得到與當前時間差
NSTimeInterval timeInterval = [timeDate timeIntervalSinceNow];
timeInterval = -timeInterval;
long temp = 0;
NSString *result;
if (timeInterval < 60) {
result = [NSString stringWithFormat:@"剛剛"];
}else if((temp = timeInterval/60) < 60){
result = [NSString stringWithFormat:@"%ld分鐘前",temp];
}else if((temp = timeInterval/3600) > 1 && (temp = timeInterval/3600) <24){
result = [NSString stringWithFormat:@"%ld小時前",temp];
}else if ((temp = timeInterval/3600) > 24 && (temp = timeInterval/3600) < 48){
result = [NSString stringWithFormat:@"昨天"];
}else if ((temp = timeInterval/3600) > 48 && (temp = timeInterval/3600) < 72){
result = [NSString stringWithFormat:@"前天"];
}else{
result = createdTimeStr;
}
NSLog(@"%@",result);
總結
以上就是這篇文字的全部內容了,希望本文的內容對各位iOS開發(fā)者能帶來一定的幫助,如果有疑問大家可以留言交流。
相關文章
Objective-C實現(xiàn)無限循環(huán)輪播器
這篇文章主要介紹了Objective-C實現(xiàn)無限循環(huán)輪播器的相關資料,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-05-05
iOS?GCD之dispatch_group_enter和dispatch_group_leave使用
這篇文章主要為大家介紹了iOS?GCD之dispatch_group_enter和dispatch_group_leave使用詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-03-03
iOS開發(fā)中Quartz2D繪圖路徑的使用以及條紋效果的實現(xiàn)
這篇文章主要介紹了iOS開發(fā)中Quartz2D繪圖路徑的使用以及條紋效果的實現(xiàn),代碼基于傳統(tǒng)的Objective-C,需要的朋友可以參考下2015-11-11
設計模式開發(fā)中的備忘錄模式在iOS應用開發(fā)中的運用實例
這篇文章主要介紹了設計模式開發(fā)中的備忘錄模式在iOS應用開發(fā)中的實例,代碼為傳統(tǒng)的Objective-C,需要的朋友可以參考下2016-03-03
iOS各種ViewController控制器使用示例完整介紹
這篇文章主要為大家介紹了iOS各種ViewController控制器使用示例完整介紹,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-07-07

