datetime - Swift - Calculating elapsed time takes too long? -
my server call gives me json data date time per piece of data , want calculate time elapsed between , , load data structure. way i'm doing takes way long, there different design practice should using? follow function using right now
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 = 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 }
for performance reasons, should pull instantiation of date formatter out of method, because that's notoriously computationally intensive.
i'd suggest using datecomponentsformatter
simplify formatting of elapsed time.
so, define 2 formatters:
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; 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 }()
and function considerably simplified:
func datediff(_ string: string) -> string? { guard let date = dateformatter.date(from: string) else { return nil } return componentsformatter.string(from: date, to: date()) }
also note that:
- i used
timezone
directly, rather round-tripping throughnstimezone
; - i set
locale
en_us_posix
, should always use if source of date strings web service or database; - i eliminated conversion of “now” string , back; use
date()
directly;
the other thing looks suspicious use of ast
timezone. date strings saved in gmt/utc/zulu (e.g., rfc 3339 or iso 8601). if have control on that, that's best practice, avoiding problems if users change time zones;
Comments
Post a Comment