在Swift中将时间从24小时转换为12小时

编程入门 行业动态 更新时间:2024-10-25 11:18:15
本文介绍了在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小时

本文发布于:2023-10-30 22:55:38,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1544245.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:小时   转换为   中将   时间   Swift

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!