gpt4 book ai didi

ios - swift : How to convert String to string with time format?

转载 作者:搜寻专家 更新时间:2023-10-30 22:06:03 24 4
gpt4 key购买 nike

我的字符串值包括时间,格式为 "HH:mm" (16:50)

我必须将此值转换为 "hh:mm"格式 (04:50) 作为 SWIFT 中的字符串

我试过 NSDateFormatter 之类的

let timeFormat = NSDateFormatter()
timeFormat.dateFormat = "hh:mm"
var dateFromStr = timeFormat.dateFromString("16:50")
var strFromDate = timeFormat.stringFromDate(dateFromStr)

但它不起作用..请告诉任何解决方案。

最佳答案

你需要 2 个 NSDateFormatter,一个用于 dateFromString,一个用于 stringFromDate

let inFormatter = NSDateFormatter()
inFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
inFormatter.dateFormat = "HH:mm"

let outFormatter = NSDateFormatter()
outFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
outFormatter.dateFormat = "hh:mm"

let inStr = "16:50"
let date = inFormatter.dateFromString(inStr)!
let outStr = outFormatter.stringFromDate(date)
println(outStr) // -> outputs 04:50

Swift 5

let inFormatter = DateFormatter()
inFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") as Locale
inFormatter.dateFormat = "hh:mm:ssa"

let outFormatter = DateFormatter()
outFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") as Locale
outFormatter.dateFormat = "hh:mm a"

let inStr = "16:50"
let datess = inFormatter.date(from: inStr)!
let outStr = outFormatter.string(from: datess)
print(outstr)

关于ios - swift : How to convert String to string with time format?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28624821/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com