Swift 我已将设备的当前时间格式设置为24小时,现在我需要使用“计算12小时格式的时间”;上午",&引用;pm";从24小时制

Swift 我已将设备的当前时间格式设置为24小时,现在我需要使用“计算12小时格式的时间”;上午",&引用;pm";从24小时制,swift,Swift,我已经将设备的当前时间格式设置为24小时,现在我想用“am”、“pm”将时间转换为12小时格式 您可以使用下面的方法。它对我有用 func toCheckTimeFormatFromDevice(){ if Date.is24HoursFormat_1 == true{ print("phone is set to 24 hours") let date = Date() let dateFormatter = DateFormatter(

我已经将设备的当前时间格式设置为24小时,现在我想用“am”、“pm”将时间转换为12小时格式

您可以使用下面的方法。它对我有用

func toCheckTimeFormatFromDevice(){
    if Date.is24HoursFormat_1 == true{
        print("phone is set to 24 hours")
        let date = Date()
        let dateFormatter = DateFormatter()
        dateFormatter.timeZone = TimeZone(abbreviation: "GMT") //Set timezone that you want
        dateFormatter.locale = NSLocale.current
        dateFormatter.dateFormat = "hh:mm a" //Specify your format that you want
        let strDate = dateFormatter.string(from: date)
        print(strDate)
    }else{
        print("phone is set to 12 hours")
    }
}

您对给定的代码有什么问题?添加到@NicoHaase:
is24HoursFormat_1
似乎不是
Date
的标准属性–您应该在解释问题的同时解释这一点;编辑您的问题,而不是在评论中回答。在那之后,肯定会有人帮助你。(顺便说一句,
==true
是多余的)首先我在设备中选择24小时格式的日期和时间格式,现在我进入应用程序,计算24小时格式的当前时间,但我需要12小时格式的时间和AM,PM。?
func convertDate12HourFormat(dateStr: String) -> String {
    let formatter = DateFormatter()
    formatter.dateFormat = "dd/MM/yyyy HH:mm"
    formatter.timeZone = TimeZone(abbreviation: "GMT+0:00")
    let dateFromStr = formatter.date(from: dateStr)
    formatter.dateFormat = "dd/MM/yyyy hh:mm a"

    let strFromDate = formatter.string(from: dateFromStr!)
    return strFromDate
}