Last active
April 7, 2018 11:33
-
-
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".
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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))) | |
} |
Awesome ! Thank you so much !
Updated to Swift 3.0
👍
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
NSDate-TimeAgo: A "time ago", "time since", "relative date", or "fuzzy date" category for NSDate and iOS, Objective-C, Cocoa Touch, iPhone, iPad