首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

iOS 秒數轉時分秒:使用 NSCalendar 與 NSDateComponents 精確計算

     編輯:程式設計綜合問答

問題

手動計算 minutes = seconds/60 會導致 61 分鐘顯示為 01:61:01 而非 02:01:01。

正確做法:日期元件運算

- (NSString *)formatSeconds:(NSInteger)totalSeconds {
    NSDate *start = [NSDate dateWithTimeIntervalSince1970:0]; // 1970-01-01 00:00:00 UTC
    NSDate *end = [start dateByAddingTimeInterval:totalSeconds];

    NSCalendar *cal = [NSCalendar currentCalendar];
    NSDateComponents *comp = [cal components:NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond
                                     fromDate:start toDate:end options:0];

    return [NSString stringWithFormat:@"%02ld:%02ld:%02ld",
            (long)comp.hour, (long)comp.minute, (long)comp.second];
}

Swift 版本

func formatSeconds(_ total: Int) -> String {
    let hours = total / 3600
    let minutes = (total % 3600) / 60
    let seconds = total % 60
    return String(format: "%02d:%02d:%02d", hours, minutes, seconds)
}

計時器場景:累積時間顯示

// 記錄開始時間
var startDate: Date?

func startTimer() {
    startDate = Date()
    Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { _ in
        self.updateLabel()
    }
}

func updateLabel() {
    guard let start = startDate else { return }
    let elapsed = Int(Date().timeIntervalSince(start))
    label.text = formatSeconds(elapsed)
}

優點

  • 自動處理進位(60秒→1分,60分→1時)。
  • 支援任意長度時間(超過 24 小時亦正確)。
  • 避免手動除法取餘的邏輯錯誤。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved