I am attempting to jot down code to easily describe how a lot time has elapsed since an occasion, however described in just one time period, eg. years, months, days, hours, minutes…
It should not present the precise elapsed time, only a normal sense of how way back it was.
I’ve written this code however it seems like there needs to be a a lot cleaner and less complicated means of doing this. Any ideas?
func fuzzyDistanceToNow(includeJustNow blIncludeJustNow: Bool, appendString stAppendString: String) -> String {
let dDistance = abs(self.distance(to: Date())) //Distance to now
let iYears = trunc(dDistance/31536000)
let iMonths = trunc(dDistance/2628000)
let iDays = trunc(dDistance/86400)
let iHours = trunc(dDistance/3600)
let iMinutes = trunc(dDistance/60)
let iSeconds = trunc(dDistance) //Not likely wanted
var sReturn: String
if iYears >= 2 {
sReturn = iYears.formatted()+" years"
} else if iYears == 1 {
sReturn = "1 yr"
} else if iMonths >= 2 {
sReturn = iMonths.formatted()+" months"
} else if iMonths == 1 {
sReturn = "1 month"
} else if iDays >= 2 {
sReturn = iDays.formatted()+" days"
} else if iDays == 1 {
sReturn = "1 day"
} else if iHours >= 2 {
sReturn = iHours.formatted()+" hours"
} else if iHours == 1 {
sReturn = "1 hour"
} else if iMinutes >= 2 {
sReturn = iMinutes.formatted()+" minutes"
} else if iMinutes == 1 {
sReturn = "1 minute"
} else if blIncludeJustNow {
sReturn = "simply now"
} else {
sReturn = ""
}
if stAppendString != "" && sReturn != "simply now" {
sReturn += stAppendString
}
return sReturn
}
}
I’ve written the above code, however it does not really feel notably environment friendly. Are there some features or shortcuts I am lacking?