輸入字串 2013-03-14 17:35:00 +0000,使用格式 MM/dd/yyyy hh:mm:ss 解析後輸出為 03/14/2013 05:35:00,小時從 17 變為 05。
hh 代表 **12 小時制**(1-12),需配合 a (AM/PM) 使用。HH 代表 **24 小時制**(0-23),直接對應 17:35。hh 導致 17 被誤讀為 05 (PM),格式化輸出時無 AM/PM 標識顯示為 05。NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
// 解析階段:匹配原字串格式(24 制 + 時區)
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss Z"]; // Z 對應 +0000
NSDate *date = [formatter dateFromString:@"2013-03-14 17:35:00 +0000"];
// 格式化階段:按需求輸出(如 24 制)
[formatter setDateFormat:@"MM/dd/yyyy HH:mm:ss"];
NSString *result = [formatter stringFromDate:date];
// 結果:03/14/2013 17:35:00
| 符號 | 含義 | 範例 |
|---|---|---|
| yyyy | 年(4 位) | 2013 |
| MM | 月(2 位) | 03 |
| dd | 日(2 位) | 14 |
| HH | 時(24 制,0-23) | 17 |
| hh | 時(12 制,1-12) | 05 |
| mm | 分 | 35 |
| ss | 秒 | 00 |
| a | AM/PM 標識 | PM |
| Z | 時區偏移(RFC 822) | +0000 |
formatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"]; 確保月份名稱等不受系統語言影響。formatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"]; 若需統一按 UTC 解析。NSDateFormatter 創建開銷大,建議靜態單例或池化復用。