为什么使用 AM/PM 的用户看不到在 24 台设备上创建的时间


  1. 在我的应用程序中,用户选择一个日期,所选日期显示在其他用户手机的底部表格中
  2. 如果两个用户的手机都在12小时区域(AM-PM(,就没有问题
  3. 如果在12时区使用手机的用户向使用24时区的用户发送时钟,则时间似乎是成功的
  4. 然而,如果使用24个时区的用户向使用12个时区的使用者发送时钟,则使用者无法看到时间。因为函数返回nil。(我使用ÖÖ和ÖS控制,因为土耳其时间失真。上午/下午(
func utcTime(dateStr: String) -> String? {
let isCurrentDevice12HoursFormat = DateFormatter.dateFormat(fromTemplate: "j", options: 0, locale: Locale.current)?.range(of: "a") != nil
let isDateStr12HoursFormat = dateStr.last == "M"
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
let isPM = dateStr.contains("ÖS")
let isAM = dateStr.contains("ÖÖ")
dateFormatter.amSymbol = isAM ? "ÖÖ" : "AM"
dateFormatter.pmSymbol = isPM ? "ÖS" : "PM"
if dateStr.contains("ÖÖ") || dateStr.contains("ÖS") {
dateFormatter.dateFormat = "yyyy-MM-dd a h:mm:ss"
} else {
dateFormatter.dateFormat = isDateStr12HoursFormat ? "yyyy-MM-dd' 'h:mm:ss a" : "yyyy-MM-dd HH:mm:ss"
}
if let date = dateFormatter.date(from: dateStr) {
dateFormatter.timeZone = TimeZone.current
dateFormatter.dateFormat = isCurrentDevice12HoursFormat ? "yyyy-MM-dd' 'h:mm:ss a" : "yyyy-MM-dd' 'HH:mm:ss"
return dateFormatter.string(from: date)
}
return nil
}

这一行解决了我的问题

dateFormatter.locale = Locale(identifier: "en_US_POSIX")

最新更新