您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 時間顯示優化:剛剛、幾分鐘前、幾小時前、昨天、前天

編輯:iOS 開發綜合

需求背景

做過動態流的人應該都不陌生:像 QQ 空間那樣,好友發表的內容下方會顯示「剛剛」「5 分鐘前」「3 小時前」「昨天」這類相對時間,而不是一串冷冰冰的日期字串。下面分兩個層次來實作。

第一版:剛剛、幾分鐘前、幾小時前

NSString *createdTimeStr = @"2017-01-01 21:05:10";

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";

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);

幾個實務上的提醒

第一,timeIntervalSinceNow 回傳的是「目標時間減去現在」,未來時間會是負值,所以這裡用 -timeInterval 轉為正的經過秒數,這個細節很容易寫錯。

第二,用除法做區間判斷雖然直觀,但邊界值(例如剛好 60 秒、剛好 24 小時)容易出現縫隙。如果專案對精度要求高,建議改成先換算成單一單位再逐層比大小,或者直接抽出獨立的工具方法複用。

第三,NSDateFormatter 建立成本不低,若是在 cellForRowAtIndexPath: 這類高頻路徑中使用,強烈建議做快取或改用 NSDateComponentsFormatter,避免列表滾動時掉幀。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved