我的服务器调用为我提供了每个数据的日期时间的 JSON数据,我想计算从现在到现在之间经过的时间并将其加载到我的数据结构中.我正在做的方式现在需要很长时间,我应该使用不同的设
func dateDiff(_ dateStr:String) -> String {
var timeAgo = "10m"
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd' 'HH:mm:ss"
formatter.timeZone = NSTimeZone(name: "AST") as! TimeZone
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd' 'HH:mm:ss"
dateFormatter.timeZone = NSTimeZone(name: "AST") as! TimeZone
let now = formatter.string(from: Date())
if let date = formatter.date(from: dateStr){
if let nowDate = formatter.date(from: now){
let components = Calendar.current.dateComponents([.day,.hour,.minute,.second], from: date, to: nowDate)
let sec = components.second
let min = components.minute
let hours = components.hour
let days = components.day
if (sec! > 0){
if let secc = sec {
timeAgo = "\(secc)s"
}
}
if (min! > 0){
if let minn = min {
timeAgo = "\(minn)m"
} }
if(hours! > 0){
if let hourss = hours {
timeAgo = "\(hourss)h"
}
}
if(days! > 0){
if let dayss = days {
timeAgo = "\(dayss)d"
}
}
}
}
return timeAgo
}
出于性能原因,您应该将日期格式化程序的实例化从方法中拉出来,因为这是众所周知的计算密集型.
我还建议使用DateComponentsFormatter来简化已用时间的格式.
因此,定义两个格式化程序:
let dateFormatter: DateFormatter = {
let _formatter = DateFormatter()
_formatter.dateFormat = "yyyy-MM-dd' 'HH:mm:ss"
_formatter.locale = Locale(identifier: "en_US_POSIX")
_formatter.timeZone = TimeZone(abbreviation: "AST") // Curious; we usually use `TimeZone(secondsFromGMT: 0)` (i.e. GMT/UTC/Zulu)
return _formatter
}()
let componentsFormatter: DateComponentsFormatter = {
let _formatter = DateComponentsFormatter()
_formatter.maximumUnitCount = 1
_formatter.unitsStyle = .abbreviated
return _formatter
}()
然后你的功能大大简化了:
func dateDiff(_ string: String) -> String? {
guard let date = dateFormatter.date(from: string) else { return nil }
return componentsFormatter.string(from: date, to: Date())
}
另请注意:
>我直接使用TimeZone,而不是通过NSTimeZone进行往返;
>我将语言环境设置为en_US_POSIX,如果日期字符串的来源是Web服务或数据库,则应该为always use;
>我将“now”转换为字符串并返回;只需直接使用Date();
唯一看起来可疑的事情是使用AST作为时区.通常日期字符串保存在GMT / UTC / Zulu中(例如,RFC 3339或ISO 8601).如果您可以控制,那可能是最佳做法,如果用户更改时区,可以避免出现问题;
