時間戳(Timestamp)通常指從 1970年1月1日 00:00:00 UTC(Unix 紀元)到當前時刻的總秒數或毫秒數。iOS/macOS 中 NSTimeInterval 以秒為單位的 double 表示。
NSString *timestampStr = @"1283376197"; // 秒級字符串 NSTimeInterval timeInterval = [timestampStr doubleValue]; NSDate *date = [NSDate dateWithTimeIntervalSince1970:timeInterval]; NSLog(@"Date: %@", date); // 輸出 GMT 時間
若為毫秒級時間戳(13位),需除以 1000.0:
long long ms = 1283376197000; NSDate *date = [NSDate dateWithTimeIntervalSince1970:ms / 1000.0];
NSDate *now = [NSDate date]; // 當前時間 NSTimeInterval interval = [now timeIntervalSince1970]; // 秒級 double NSString *timestamp = [NSString stringWithFormat:@"%.0f", interval]; // 秒級字符串 // 毫秒級 NSString *msTimestamp = [NSString stringWithFormat:@"%.0f", interval * 1000];
原文中的時區轉換代碼(NSTimeZone 調整)實際上是多餘的,timeIntervalSince1970 已經返回 UTC 基準的秒數,無需手動時區修正。
NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; [formatter setDateFormat:@"yyyy年MM月dd日 HH:mm:ss"]; // 自定義格式 formatter.timeZone = [NSTimeZone systemTimeZone]; // 顯示本地時間 NSString *dateStr = [formatter stringFromDate:date]; NSLog(@"Formatted: %@", dateStr);
| 符號 | 含義 | 示例 |
|---|---|---|
| yyyy | 年(4位) | 2024 |
| MM | 月(2位) | 01-12 |
| dd | 日(2位) | 01-31 |
| HH | 時(24制) | 00-23 |
| mm | 分 | 00-59 |
| ss | 秒 | 00-59 |
| SSS | 毫秒 | 000-999 |
NSDateFormatter *parser = [[NSDateFormatter alloc] init]; [parser setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; [parser setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]]; // 指定輸入時區 NSDate *parsedDate = [parser dateFromString:@"2024-01-15 14:30:00"];
// DateUtils.h
@interface DateUtils : NSObject
+ (NSString *)timestampFromDate:(NSDate *)date milliseconds:(BOOL)ms;
+ (NSDate *)dateFromTimestamp:(NSString *)timestamp milliseconds:(BOOL)ms;
+ (NSString *)stringFromDate:(NSDate *)date format:(NSString *)fmt;
@end
// DateUtils.m
@implementation DateUtils
+ (NSString *)timestampFromDate:(NSDate *)date milliseconds:(BOOL)ms {
NSTimeInterval ti = [date timeIntervalSince1970];
return ms ? [NSString stringWithFormat:@"%.0f", ti * 1000] : [NSString stringWithFormat:@"%.0f", ti];
}
+ (NSDate *)dateFromTimestamp:(NSString *)timestamp milliseconds:(BOOL)ms {
NSTimeInterval ti = [timestamp doubleValue];
if (ms) ti /= 1000.0;
return [NSDate dateWithTimeIntervalSince1970:ti];
}
+ (NSString *)stringFromDate:(NSDate *)date format:(NSString *)fmt {
NSDateFormatter *f = [[NSDateFormatter alloc] init];
f.dateFormat = fmt;
f.timeZone = [NSTimeZone systemTimeZone];
return [f stringFromDate:date];
}
@end
NSDate 內部存儲 UTC,顯示時才按時區格式化。存儲/傳輸用時間戳或 ISO8601 字符串(yyyy-MM-dd'T'HH:mm:ssZ)。NSTimeInterval 是 double,秒級精度約 15-16 位有效數字,毫秒級足夠,納秒級會丟失精度。NSDateFormatter 創建開銷大,高頻調用時應緩存實例或使用靜態單例。