Convert an array of times from 24hr to 12 hr in Swift

狂风中的少年 提交于 2019-12-05 23:20:20

You're not using the right value for the conversion: your two variable is always the first item of the array.

Just use twelve instead, which represents each item in the array while looping:

for twelve in arrayTimes {

    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "H:mm"
    let date12 = dateFormatter.dateFromString(twelve)!

    dateFormatter.dateFormat = "h:mm a"
    let date22 = dateFormatter.stringFromDate(date12)

    print(date22)

    print("output \(twelve)")
}

Also, just a tip: it's not needed to create a new formatter each time the loops iterates, you can declare the formatter only once, outside the loop. And be careful with force-unwrapped optionals, I prefer to use if let or any other known method like guard.

Example with if let:

let dateFormatter = NSDateFormatter()

for twelve in arrayTimes {

    dateFormatter.dateFormat = "H:mm"
    if let date12 = dateFormatter.dateFromString(twelve) {
        dateFormatter.dateFormat = "h:mm a"
        let date22 = dateFormatter.stringFromDate(date12)
        print(date22)
        print("output \(twelve)")
    } else {
        // oops, error while converting the string
    }

}

If you would like to change your array you can use enumerate and use that index to change the array element:

Swift 3 or later

var arrayTimes = ["16:00", "16:30", "17:00", "17:30", "18:00", "18:30"]

let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
for (index,time) in arrayTimes.enumerated() {
    dateFormatter.dateFormat = "H:mm"
    if let inDate = dateFormatter.date(from: time) {
        dateFormatter.dateFormat = "h:mm a"
        let outTime = dateFormatter.string(from:inDate)
        print("in \(time)")
        print("out \(outTime)")
        arrayTimes[index] = outTime
    }

}

print(arrayTimes)  // "4:00 PM", "4:30 PM", "5:00 PM", "5:30 PM", "6:00 PM", "6:30 PM"]

Swift 2

var arrayTimes = ["16:00", "16:30", "17:00", "17:30", "18:00", "18:30"]

let dateFormatter = NSDateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
for (index,time) in arrayTimes.enumerate() {
    dateFormatter.dateFormat = "H:mm"
    if let inDate = dateFormatter.dateFromString(time) {
        dateFormatter.dateFormat = "h:mm a"
        let outTime = dateFormatter.stringFromDate(inDate)
        print("in \(time)")
        print("out \(outTime)")
        arrayTimes[index] = outTime
    }

}


print(arrayTimes)  // "4:00 PM", "4:30 PM", "5:00 PM", "5:30 PM", "6:00 PM", "6:30 PM"]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!