iOS實(shí)現(xiàn)時(shí)間顯示幾分鐘前,幾小時(shí)前以及剛剛的方法示例
前言
本文實(shí)現(xiàn)的效果類似于QQ空間里的好友發(fā)表的動(dòng)態(tài),會(huì)顯示好友發(fā)表的時(shí)間,這里是處理顯示幾小時(shí)前,幾分鐘前,剛剛,昨天,前天這樣的格式,下面來(lái)一起看看吧。
一:剛剛,幾分鐘前,幾小時(shí)前
//時(shí)間
NSString *createdTimeStr = @"2017-01-01 21:05:10";
//把字符串轉(zhuǎn)為NSdate
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *timeDate = [dateFormatter dateFromString:createdTimeStr];
//得到與當(dāng)前時(shí)間差
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小時(shí)前",temp];
}else{
result = createdTimeStr;
}
NSLog(@"%@",result);
二:剛剛,幾分鐘前,幾小時(shí)前,昨天,前天
//時(shí)間
NSString *createdTimeStr = @"2017-01-01 21:05:10";
//把字符串轉(zhuǎn)為NSdate
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *timeDate = [dateFormatter dateFromString:createdTimeStr];
//得到與當(dāng)前時(shí)間差
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小時(shí)前",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);
總結(jié)
以上就是這篇文字的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)各位iOS開發(fā)者能帶來(lái)一定的幫助,如果有疑問大家可以留言交流。
相關(guān)文章
iOS App開發(fā)中使cell高度自適應(yīng)的黑魔法詳解
這篇文章主要介紹了iOS App開發(fā)中使cell高度自適應(yīng)的黑魔法詳解,作者利用iOS8以后的新特性講解了TableView、CollectionView中的cell高度自適應(yīng)以及UITextView輸入內(nèi)容實(shí)時(shí)更新cell高度的方法,需要的朋友可以參考下2016-03-03
IOS 遠(yuǎn)程通知兼容(IOS7,IOS8)實(shí)例詳解
這篇文章主要介紹了IOS 遠(yuǎn)程通知兼容(IOS7,IOS8)實(shí)例詳解的相關(guān)資料,需要的朋友可以參考下2017-03-03
IOS ObjectC與javascript交互詳解及實(shí)現(xiàn)代碼
這篇文章主要介紹了IOS OC與js交互詳解及實(shí)現(xiàn)代碼的相關(guān)資料,需要的朋友可以參考下2017-03-03
iOS實(shí)現(xiàn)類似微信和支付寶的密碼輸入框(UIKeyInput協(xié)議)
這篇文章主要介紹了iOS實(shí)現(xiàn)類似微信和支付寶的密碼輸入框,通過UIKeyInput協(xié)議為響應(yīng)者提供簡(jiǎn)單的鍵盤輸入的功,再通過CoreGraphics繪制出密碼輸入框,感興趣的小伙伴們可以參考一下2016-08-08
iOS開發(fā)中常見的項(xiàng)目文件與MVC結(jié)構(gòu)優(yōu)化思路解析
這篇文章主要介紹了iOS開發(fā)中常見的項(xiàng)目文件與MVC結(jié)構(gòu)優(yōu)化思路解析,示例代碼基于傳統(tǒng)的Objective-C,需要的朋友可以參考下2015-12-12

