Skip to content

Instantly share code, notes, and snippets.

@01taylop
Last active April 7, 2018 11:33
Show Gist options
  • Save 01taylop/61888ad1e74bfcd4f739 to your computer and use it in GitHub Desktop.
Save 01taylop/61888ad1e74bfcd4f739 to your computer and use it in GitHub Desktop.
A very simple date time ago file in swift inspired from kevinlawler's "NSDate-TimeAgo".
//
// DateTimeAgo.swift
//
// Created by Patrick Taylor on 30/01/2016.
// Copyright © 2016 Patrick Taylor. All rights reserved.
//
import Foundation
import Darwin
func dateTimeAgo(date: Date) -> String {
let deltaSeconds = secondsFrom(date: date)
let deltaMinutes:Double = Double(deltaSeconds / 60)
if deltaSeconds < 5 {
return "Just now"
}
if deltaSeconds < 60 {
return String(deltaSeconds) + " seconds ago"
}
if deltaSeconds < 120 {
return "A minute ago"
}
if deltaMinutes < 60 {
return String(Int(deltaMinutes)) + " minutes ago"
}
if deltaMinutes < 120 {
return "An hour ago"
}
if deltaMinutes < (24 * 60) {
let hours = flooredString(delta: deltaMinutes, dividedBy: 60)
return hours + " hours ago"
}
if deltaMinutes < (24 * 60 * 2) {
return "Yesterday"
}
if deltaMinutes < (24 * 60 * 7) {
let days = flooredString(delta: deltaMinutes, dividedBy: (60 * 24))
return days + " days ago"
}
if deltaMinutes < (24 * 60 * 14) {
return "Last week"
}
if deltaMinutes < (24 * 60 * 31) {
let weeks = flooredString(delta: deltaMinutes, dividedBy: (60 * 24 * 7))
return weeks + " weeks ago"
}
if deltaMinutes < (24 * 60 * 61) {
return "Last month"
}
if deltaMinutes < (24 * 60 * 365.25) {
let months = flooredString(delta: deltaMinutes, dividedBy: (60 * 24 * 30))
return months + " months ago"
}
if deltaMinutes < (24 * 60 * 731) {
return "Last year"
}
let years = flooredString(delta: deltaMinutes, dividedBy: (60 * 24 * 365))
return years + " years ago"
}
private func secondsFrom(date:Date) -> Int {
return Calendar.current.dateComponents([.second], from: date, to: Date()).second ?? 0
}
private func flooredString(delta: Double, dividedBy: Double) -> String {
return String(Int(floor(delta/dividedBy)))
}
@lemonlab
Copy link

Awesome ! Thank you so much !

@01taylop
Copy link
Author

01taylop commented Jan 7, 2017

Updated to Swift 3.0

@lemonlab
Copy link

👍

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