Swift 3-UTC时间标签,考虑12h / 24h设备时间更改 [英] Swift 3 - UTC to time ago label, thinking 12h / 24h device time changes
本文介绍了Swift 3-UTC时间标签,考虑12h / 24h设备时间更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将timeUTC转换为 5s ago。以前的标签还考虑在手机上进行12h / 24h更改。因为出事了。现在下面的代码行返回标签值,我想要在操场上。但是不在我的ios项目上。它不会进入If块。我丢失了什么或怎么了?
I want to convert timeUTC to "5s ago." ago label also thinking 12h / 24h changes on the phone. Because goes crash. Now below lines of code return label value what I want in the Playground. But not on my ios project. It doesn't go into If block. What I'm missing or What's the wrong with that?
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"
}
}
}
推荐答案
要将此字符串转换为日期,我会这样做:
To convert this string to a date, I would do:
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
,例如:
Then, to show the elapsed time in a nice format, consider DateComponentsFormatter
, e.g.:
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")
这篇关于Swift 3-UTC时间标签,考虑12h / 24h设备时间更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文