gpt4 book ai didi

ios - Swift 3 - UTC to time ago 标签,考虑 12h/24h 设备时间变化

转载 作者:搜寻专家 更新时间:2023-11-01 07:17:13 25 4
gpt4 key购买 nike

我想将 timeUTC 转换为“5 秒前”。前标签还考虑 12h/24h 在手机上的变化。因为会崩溃。现在下面的代码行返回我在 Playground 中想要的标签值。但不是在我的 ios 项目上。它不会进入 If block 。我缺少什么或那有什么问题?

    let dateStringUTC = "2016-10-22 12:37:48 +0000"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss ZZZ"

if let from = dateFormatter.date(from: dateStringUTC) {

dateFormatter.dateFormat = "MMM d, yyyy h:mm:ss a"
let stringFromDate = dateFormatter.string(from: from)
let dateLast = dateFormatter.date(from: stringFromDate)

let now = Date()
let components: NSCalendar.Unit = [.second, .minute, .hour, .day, .weekOfMonth]
let difference = (Calendar.current as NSCalendar).components(components, from: dateLast!, to: now, options: [])

if difference.second! <= 0 {
self.timeInfoLbl.text = "now"
}
if difference.second! > 0 && difference.minute! == 0 {
self.timeInfoLbl.text = String(describing: difference.second!) + "s."
}
if difference.minute! > 0 && difference.hour! == 0 {
self.timeInfoLbl.text = String(describing: difference.minute!) + "m."
}
if difference.hour! > 0 && difference.day! == 0 {
self.timeInfoLbl.text = String(describing: difference.hour!) + "h."
}
if difference.day! > 0 && difference.weekOfMonth! == 0 {
self.timeInfoLbl.text = String(describing: difference.day!) + "d."
}
if difference.weekOfMonth! > 0 {
self.timeInfoLbl.text = String(describing: difference.weekOfMonth!) + "w."

if difference.weekOfMonth! > 52 {
let number = Float(difference.weekOfMonth!) / 52
let strYear = String(format:"%.1f", number)
self.timeInfoLbl.text = strYear + " year"
}
}
}

最佳答案

要将此字符串转换为日期,我会这样做:

let dateStringUTC = "2016-10-22 12:37:48 +0000"
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss X"
let date = dateFormatter.date(from: dateStringUTC)!

然后,要以良好的格式显示耗时,请考虑 DateComponentsFormatter,例如:

let now = Date()

let formatter = DateComponentsFormatter()
formatter.unitsStyle = .full
formatter.maximumUnitCount = 2
let string = formatter.string(from: date, to: Date())! + " " + NSLocalizedString("ago", comment: "added after elapsed time to say how long before")

关于ios - Swift 3 - UTC to time ago 标签,考虑 12h/24h 设备时间变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41515980/

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