Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 6 additions & 5 deletions Sources/LocalizedTimeAgo/LocalizedTimeAgo.swift
Original file line number Diff line number Diff line change
Expand Up @@ -60,13 +60,13 @@ public extension Date {

private var calendar: Calendar { return .current }

private var components: DateComponents {
private func components(relativeTo referenceDate: Date = Date()) -> DateComponents {
let unitFlags = Set<Calendar.Component>([.second,.minute,.hour,.day,.weekOfYear,.month,.year])
let now = Date()
return calendar.dateComponents(unitFlags, from: self, to: now)
return calendar.dateComponents(unitFlags, from: self, to: referenceDate)
}

func timeAgo(numericDates: Bool = false, numericTimes: Bool = false) -> String {
func timeAgo(numericDates: Bool = false, numericTimes: Bool = false, relativeTo referenceDate: Date = Date()) -> String {
let components = self.components(relativeTo: referenceDate)
if let year = components.year, year > 0 {
if year >= 2 { return String(format: "%d years ago".adjustedKey(forValue: year).localized(), year) }
return numericDates ? "1 year ago".localized() : "Last year".localized()
Expand All @@ -92,7 +92,8 @@ public extension Date {
return numericTimes ? "1 second ago".localized() : "Just now".localized()
}

func shortTimeAgo() -> String {
func shortTimeAgo(relativeTo referenceDate: Date = Date()) -> String {
let components = self.components(relativeTo: referenceDate)
if let year = components.year, year > 0 {
return String(format: "%dy".localized(), year)
} else if let month = components.month, month > 0 {
Expand Down