您的问题有点令人困惑。我假设您想要输入一个看起来像“2021 年 1 月 15 日 22:05”(24 小时时间)或“2021 年 1 月 15 日晚上 10:05”(12 小时时间)的输入日期并将其转换为标准“互联网日期”ISO8601DateFormatter 日期格式。
您说要根据“设备选择”确定输入选择。我假设您的意思是您希望根据用户设备上的设置以 12 或 24 小时格式查看输入日期。
此功能可让您了解用户设备的 12/24 小时设置:
func dateFormatIs24Hour() -> Bool {
guard let dateFormat = DateFormatter.dateFormat (fromTemplate: "j",
options:0,
locale: Locale.current) else {
return false
}
return !dateFormat.contains("a")
}
然后您应该能够根据设备的 12/24 小时设置生成日期格式化程序 formatString:
func MMMddyyyyDateFormat(twentyFourHour: Bool) -> String {
let hourFormat = is24Hour ? "HH" : "hh"
let amOrPmSuffix = is24Hour ? "" : "a"
let dateFormat = "MMM dd, yyyy \(hourFormat):mm \(amOrPmSuffix)"
return dateFormat
}
您可以设置 ISO8601DateFormatter 以“互联网日期格式”输出日期:
let internetDateFormatter = ISO8601DateFormatter()
internetDateFormatter.formatOptions = .withInternetDateTime
在一个 shell iOS 应用程序的示例 viewDidLoad() 函数中将所有内容整合在一起:
override func viewDidLoad() {
super.viewDidLoad()
is24Hour = dateFormatIs24Hour()
let inputDateFormatter = DateFormatter()
inputDateFormatter.dateFormat = MMMddyyyyDateFormat(twentyFourHour: is24Hour)
let internetDateFormatter = ISO8601DateFormatter()
internetDateFormatter.formatOptions = .withInternetDateTime
//-----------------------------------------
//This code to generate a value `randomDate` using `thirtyDays` is
//only for testing. It generates a random date that is in a range
//from roughly 30 days in the past to 30 days in the future.
let thirtyDays = 30.0 * 24 * 60 * 60
let randomInterval = Double.random(in: -thirtyDays...thirtyDays)
let randomDate = Date().addingTimeInterval(randomInterval)
//-----------------------------------------
let inputDateString = inputDateFormatter.string(from: randomDate)
var outputDateString = ""
if let convertedDate = inputDateFormatter.date(from: inputDateString) {
outputDateString = internetDateFormatter.string(from: convertedDate)
}
print("Date string \(inputDateString) in Internet format = \(outputDateString)")
}