Swift中DateFormatter的HH格式未输出24小时制时间问题求助
This is a classic edge case tied to iOS 11.x's date formatter behavior—you’re absolutely right to suspect the older system version here. Here’s what’s happening and how to fix it:
The Root Cause
On iOS 11.2 and some earlier minor versions, even when you set the time zone to UTC, the DateFormatter (or NSDateFormatter for Objective-C) might still respect the device’s regional time format preferences (12-hour vs 24-hour) if you don’t explicitly lock down the locale. This inconsistency doesn’t appear on newer iOS versions or even same-version devices like your iPhone X, likely because those devices have 24-hour format enabled in system settings, while your cousin’s iPhone doesn’t.
The Solution: Force POSIX Locale
To guarantee 24-hour format output regardless of device settings or iOS version, you need to set the formatter’s locale to en_POSIX. This locale is standardized and ignores system-level regional preferences, ensuring your format string is interpreted exactly as written.
Swift Example:
let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss" // "HH" = 24-hour format dateFormatter.timeZone = TimeZone(identifier: "UTC") // Critical line to bypass system locale preferences dateFormatter.locale = Locale(identifier: "en_POSIX") let currentUTCTime = dateFormatter.string(from: Date()) print(currentUTCTime) // Will always output 24-hour format
Objective-C Example:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; [dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]]; // Lock locale to POSIX to avoid regional overrides [dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_POSIX"]]; NSString *currentUTCTime = [dateFormatter stringFromDate:[NSDate date]]; NSLog(@"%@", currentUTCTime);
Key Notes
- Always use
HH(uppercase) for 24-hour format in your date string—hh(lowercase) is for 12-hour format. - The
en_POSIXlocale is safe to use globally; it won’t affect the language of your date output unless you’re using localized date components (which you aren’t here, since you’re using a fixed format string).
内容的提问来源于stack exchange,提问作者Dipen Shah

