Skip to content

Instantly share code, notes, and snippets.

@BrandonShega
Last active September 11, 2019 02:12
Show Gist options
  • Save BrandonShega/e745ddb4d66a8efeabe504614fd58084 to your computer and use it in GitHub Desktop.
Save BrandonShega/e745ddb4d66a8efeabe504614fd58084 to your computer and use it in GitHub Desktop.
Relative Time
extension NSDate {
var relativeTime: String {
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Second, .Minute, .Hour, .Day, .Month, .Year], fromDate: self, toDate: NSDate(), options: [])
if components.year > 0 {
if components.year < 2 {
return "Last year"
} else {
return "\(components.year) years ago"
}
}
if components.month > 0 {
if components.month < 2 {
return "Last month"
} else {
return "\(components.month) months ago"
}
}
if components.day >= 7 {
let week = components.day/7
if week < 2 {
return "Last week"
} else {
return "\(week) weeks ago"
}
}
if components.day > 0 {
if components.day < 2 {
return "Yesterday"
} else {
return "\(components.day) days ago"
}
}
if components.hour > 0 {
if components.hour < 2 {
return "An hour ago"
} else {
return "\(components.hour) hours ago"
}
}
if components.minute > 0 {
if components.minute < 2 {
return "A minute ago"
} else {
return "\(components.minute) minutes ago"
}
}
if components.second > 0 {
if components.second < 5 {
return "Just now"
} else {
return "\(components.second) seconds ago"
}
}
return ""
}
}
@timvermeulen
Copy link

Swift 3:

extension Date {
    var relativeTime: String {

        let calendar = Calendar.current
        let components = calendar.dateComponents([.second, .minute, .hour, .day, .month, .year], from: self, to: Date())

        if let years = components.year, years > 0 {
            return  years == 1 ? "Last year" : "\(years) years ago"
        }
        else if let months = components.month, months > 0 {
            return months == 1 ? "Last month" : "\(months) months ago"
        }
        else if let days = components.day, days > 0 {
            let weeks = days / 7
            if weeks > 0 { return weeks == 1 ? "Last week" : "\(weeks) weeks ago" }
            else { return days == 1 ? "Yesterday" : "\(days) days ago" }
        }
        else if let hours = components.hour, hours > 0 {
            return hours == 1 ? "An hour ago" : "\(hours) hours ago"
        }
        else if let minutes = components.minute, minutes > 0 {
            return minutes == 1 ? "A minute ago" : "\(minutes) minutes ago"
        }
        else if let seconds = components.second, seconds >= 5 {
            return "\(seconds) seconds ago"
        }
        else { return "Just now" }
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment