iOS 日期格式化核心類,支援「日期 → 字串」與「字串 → 日期」雙向轉換。執行緒不安全,頻繁使用建議快取或每次新建。
// 1. 建立格式化器
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
// 2. 設定日期格式(Unicode Technical Standard #35)
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
// 3. 取得當前時間
NSDate *now = [NSDate date];
// 4. 日期 → 字串
NSString *dateString = [formatter stringFromDate:now];
// 結果:2024-01-15 14:30:45
NSLog(@"%@", dateString);
// 5. 釋放(MRC 環境)
[formatter release];
| 符號 | 意義 | 範例輸出 |
|---|---|---|
| y / yyyy | 年 | 2024 / 24 |
| M / MM / MMM / MMMM | 月(數字/縮寫/全名) | 1 / 01 / Jan / January |
| d / dd | 日 | 5 / 05 |
| E / EEE / EEEE | 星期(縮寫/全名) | Mon / Monday |
| a | AM/PM | AM / PM |
| h / hh | 12 小時制時 | 2 / 02 |
| H / HH | 24 小時制時 | 14 / 14 |
| m / mm | 分 | 5 / 05 |
| s / ss | 秒 | 9 / 09 |
| S / SS / SSS | 毫秒 | 5 / 05 / 005 |
| z / zzzz | 時區名稱 | GMT+08:00 / China Standard Time |
| Z / ZZZZZ | 時區偏移 | +0800 / +08:00 |
// ISO 8601 標準(API 交換首選)
@"yyyy-MM-dd'T'HH:mm:ssZZZZZ" // 2024-01-15T14:30:45+08:00
@"yyyy-MM-dd'T'HH:mm:ss.SSSZ" // 含毫秒
// 純日期
@"yyyy-MM-dd" // 2024-01-15
@"yyyy年MM月dd日" // 2024年01月15日
// 純時間
@"HH:mm:ss" // 14:30:45
@"hh:mm a" // 02:30 PM
// 中文常用
@"M月d日 HH:mm" // 1月15日 14:30
@"yyyy/M/d EEEE" // 2024/1/15 星期一
// 檔案命名安全格式
@"yyyyMMdd_HHmmss" // 20240115_143045
+ (NSString *)dateStringFromTimestamp:(NSTimeInterval)timestamp
format:(NSString *)formatString {
NSDate *date = [NSDate dateWithTimeIntervalSince1970:timestamp];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:formatString];
// 建議設定 locale 避免 24/12 小時制歧義
[formatter setLocale:[NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"]];
NSString *str = [formatter stringFromDate:date];
return str;
}
// 使用
NSTimeInterval ts = [[NSDate date] timeIntervalSince1970]; // 當前時間戳
NSString *str = [self dateStringFromTimestamp:ts format:@"yyyy-MM-dd HH:mm:ss"];
NSDateFormatter *parser = [[NSDateFormatter alloc] init];
[parser setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
[parser setLocale:[NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"]];
NSString *input = @"2024-01-15 14:30:45";
NSDate *date = [parser dateFromString:input];
if (date) {
NSLog(@"解析成功: %@", date);
} else {
NSLog(@"格式不符,無法解析");
}
NSDateFormatter 建立開銷大,高頻呼叫必須快取:
// 單例快取管理器
@interface DateFormatterCache : NSObject
+ (NSDateFormatter *)formatterWithFormat:(NSString *)format;
@end
@implementation DateFormatterCache
+ (NSDateFormatter *)formatterWithFormat:(NSString *)format {
static NSMutableDictionary *cache;
static dispatch_once_t once;
dispatch_once(&once, ^{ cache = [NSMutableDictionary dictionary]; });
NSDateFormatter *formatter = cache[format];
if (!formatter) {
formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = format;
formatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
formatter.timeZone = [NSTimeZone systemTimeZone];
cache[format] = formatter;
}
return formatter;
}
@end
// 使用
NSDateFormatter *fmt = [DateFormatterCache formatterWithFormat:@"yyyy-MM-dd"];
NSString *str = [fmt stringFromDate:[NSDate date]];
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(secondsFromGMT: 0)
let now = Date()
let string = formatter.string(from: now) // 日期 -> 字串
if let date = formatter.date(from: "2024-01-15 14:30:45") { // 字串 -> 日期
print(date)
}
// ISO8601 專用解析器(iOS 10+)
let isoFormatter = ISO8601DateFormatter()
isoFormatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
let isoString = isoFormatter.string(from: Date())