Skip to content

Commit

Permalink
Merge pull request melvitax#30 from sahandnayebaziz/master
Browse files Browse the repository at this point in the history
add support for future times to relativeTimeToString()
  • Loading branch information
melvitax committed Apr 1, 2016
2 parents 360126c + 8ef1960 commit e1f35f5
Showing 1 changed file with 15 additions and 8 deletions.
23 changes: 15 additions & 8 deletions AFDateHelper/AFDateExtension.swift
Original file line number Diff line number Diff line change
Expand Up @@ -816,41 +816,48 @@ public extension NSDate {
let time = self.timeIntervalSince1970
let now = NSDate().timeIntervalSince1970

let seconds = now - time
let timeIsInPast = now - time > 0

let seconds = abs(now - time)
let minutes = round(seconds/60)
let hours = round(minutes/60)
let days = round(hours/24)

func describe(time: String) -> String {
if timeIsInPast { return "\(time) ago" }
else { return "in \(time)" }
}

if seconds < 10 {
return NSLocalizedString("just now", comment: "Show the relative time from a date")
} else if seconds < 60 {
let relativeTime = NSLocalizedString("%.f seconds ago", comment: "Show the relative time from a date")
let relativeTime = NSLocalizedString(describe("%.f seconds"), comment: "Show the relative time from a date")
return String(format: relativeTime, seconds)
}

if minutes < 60 {
if minutes == 1 {
return NSLocalizedString("1 minute ago", comment: "Show the relative time from a date")
return NSLocalizedString(describe("1 minute"), comment: "Show the relative time from a date")
} else {
let relativeTime = NSLocalizedString("%.f minutes ago", comment: "Show the relative time from a date")
let relativeTime = NSLocalizedString(describe("%.f minutes"), comment: "Show the relative time from a date")
return String(format: relativeTime, minutes)
}
}

if hours < 24 {
if hours == 1 {
return NSLocalizedString("1 hour ago", comment: "Show the relative time from a date")
return NSLocalizedString(describe("1 hour"), comment: "Show the relative time from a date")
} else {
let relativeTime = NSLocalizedString("%.f hours ago", comment: "Show the relative time from a date")
let relativeTime = NSLocalizedString(describe("%.f hours"), comment: "Show the relative time from a date")
return String(format: relativeTime, hours)
}
}

if days < 7 {
if days == 1 {
return NSLocalizedString("1 day ago", comment: "Show the relative time from a date")
return NSLocalizedString(describe("1 day"), comment: "Show the relative time from a date")
} else {
let relativeTime = NSLocalizedString("%.f days ago", comment: "Show the relative time from a date")
let relativeTime = NSLocalizedString(describe("%.f days"), comment: "Show the relative time from a date")
return String(format: relativeTime, days)
}
}
Expand Down

0 comments on commit e1f35f5

Please sign in to comment.