在Swift中将时间从24小时转换为12小时 [英] Convert an array of times from 24hr to 12 hr in Swift

查看:524
本文介绍了在Swift中将时间从24小时转换为12小时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的数组:

I have an array like this:

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

,我想将数组从24 hr转换为12 hr.这是到目前为止,我将数组中的第一个数字转换的方法./p>

and I want to convert the array from 24 hr to 12 hr.. This is what I have so far which converts the first number in the array.. I'm missing something but I can't work it out.

func convertTimes(){

                for twelve in arrayTimes{

                    var two = arrayTimes[0]

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

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

                    print(date22)

                    print("output \(twelve)")
                }
                }

            convertTimes()

推荐答案

您没有使用正确的值进行转换:您的two变量始终是数组的第一项.

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

只需使用twelve即可,它表示循环时数组中的每个项目:

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)")
}


还有一个提示:每次循环迭代时都不需要创建新的格式化程序,您只能在循环外部声明一次格式化程序.并且请小心使用强制展开的可选内容,我更喜欢使用if let或任何其他已知的方法,例如guard.


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.

带有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
    }

}

这篇关于在Swift中将时间从24小时转换为12小时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆