Skip to content

Instantly share code, notes, and snippets.

//
// ViewController.swift
// Quiz
//
// Created by John Regner on 7/26/14.
// Copyright (c) 2014 In Your Dreams Software. All rights reserved.
//
import UIKit
@minorbug
minorbug / timeago.swift
Created November 7, 2014 15:28
"Time ago" function for Swift (based on MatthewYork's DateTools for Objective-C)
func timeAgoSinceDate(date:NSDate, numericDates:Bool) -> String {
let calendar = NSCalendar.currentCalendar()
let unitFlags = NSCalendarUnit.CalendarUnitMinute | NSCalendarUnit.CalendarUnitHour | NSCalendarUnit.CalendarUnitDay | NSCalendarUnit.CalendarUnitWeekOfYear | NSCalendarUnit.CalendarUnitMonth | NSCalendarUnit.CalendarUnitYear | NSCalendarUnit.CalendarUnitSecond
let now = NSDate()
let earliest = now.earlierDate(date)
let latest = (earliest == now) ? date : now
let components:NSDateComponents = calendar.components(unitFlags, fromDate: earliest, toDate: latest, options: nil)
if (components.year >= 2) {
return "\(components.year) years ago"