Skip to content

Instantly share code, notes, and snippets.

@saniul
Created December 8, 2015 21:14
Show Gist options
  • Save saniul/05ba6b2566fead584530 to your computer and use it in GitHub Desktop.
Save saniul/05ba6b2566fead584530 to your computer and use it in GitHub Desktop.
NSDateComponentsFormatter Weirdness
//: Playground - noun: a place where people can play
import Foundation
let formatter = NSDateComponentsFormatter()
formatter.unitsStyle = .Abbreviated
formatter.maximumUnitCount = 1
formatter.allowsFractionalUnits = true
var allowedUnits: NSCalendarUnit = [
.Year,
.Month,
.WeekOfMonth,
.Day,
.Hour,
.Minute,
.Second
]
formatter.allowedUnits = allowedUnits
let referenceDate = NSDate(timeIntervalSince1970: 1449608914.85899)
let targetDate = NSDate(timeIntervalSince1970: 1449433057.776354)
let distance = abs(targetDate.timeIntervalSinceDate(referenceDate))
let string: String
if distance <= 60 {
string = "now"
} else {
string = formatter.stringFromDate(targetDate, toDate: referenceDate) ?? "<NO_RESULT>"
}
// string returns "2d 1h"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment