您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 使用技巧 >> iOS 7 技巧

iOS 時間與時間戳互轉:格式化、毫秒換算與間隔計算

編輯:iOS 7 技巧

後端回傳的時間多半是 1970 年以來的秒數或毫秒數,畫面上要給使用者看的卻是可讀日期。以下整理四段常用程式碼。

一、時間戳轉成可讀字串

- (NSString *)timeWithTimeIntervalString:(NSString *)timeString {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"yyyy年MM月dd日 HH:mm"];

    // 毫秒要除以 1000
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:
                        [timeString doubleValue] / 1000.0];

    return [formatter stringFromDate:date];
}

二、日期物件轉成時間戳

NSDate *date = [NSDate dateWithTimeIntervalSinceNow:0];
NSTimeInterval a = [date timeIntervalSince1970] * 1000; // 乘 1000 為毫秒
NSString *timeString = [NSString stringWithFormat:@"%.0f", a];

三、算出兩個日期相隔的年月日

- (void)getAgeWithDateString:(NSString *)date {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    NSDate *createDate = [formatter dateFromString:date];

    NSCalendar *gregorian =
        [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];

    NSUInteger unitFlags = NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear;

    NSDateComponents *components =
        [gregorian components:unitFlags
                     fromDate:createDate
                       toDate:[NSDate date]
                      options:0];

    NSInteger years  = [components year];
    NSInteger months = [components month];
    NSInteger days   = [components day];
}

實務上的三個坑

時區。不指定 timeZone 時,formatter 會跟著系統設定跑。伺服器時間若固定是 UTC,最好明確寫死時區,否則使用者出國或手動改時區後,同一筆資料會顯示成不同時間。

秒與毫秒。判斷方式很簡單:位數 10 是秒,13 是毫秒。混用會直接跳到幾十年後,畫面上出現 57405 年這種笑話。

不要用 NSDate 做月級距的相減。timeIntervalSinceDate 回傳的是固定秒數,跨月、跨閏年會算錯。凡涉及「幾個月」「幾歲」,一律交給 NSCalendar 的 components 處理。

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