Swift – 计算经过的时间需要太长时间?
发布时间:2020-12-14 04:27:31 所属栏目:百科 来源:网络整理
导读:我的服务器调用为我提供了每个数据的日期时间的 JSON数据,我想计算从现在到现在之间经过的时间并将其加载到我的数据结构中.我正在做的方式现在需要很长时间,我应该使用不同的设计实践吗?以下功能是我现在正在使用的功能 func dateDiff(_ dateStr:String) -
我的服务器调用为我提供了每个数据的日期时间的
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进行往返; 唯一看起来可疑的事情是使用AST作为时区.通常日期字符串保存在GMT / UTC / Zulu中(例如,RFC 3339或ISO 8601).如果您可以控制,那可能是最佳做法,如果用户更改时区,可以避免出现问题; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |