Skip to content

Instantly share code, notes, and snippets.

@0xtmphey
Created December 24, 2018 10:58
Show Gist options
  • Save 0xtmphey/20c661944437f6f071c917d4e75e846c to your computer and use it in GitHub Desktop.
Save 0xtmphey/20c661944437f6f071c917d4e75e846c to your computer and use it in GitHub Desktop.
import Foundation
let date1Timestamp = Double(1545648417) // This is our date since 1970
let date2Str = "2018-12-07 05:32:54" // This is our date in String
// Here we create a `DateFormatter` which will allow us to parse our String
// Since we don't have a timezone data in our String, we indicate that this String in UTC
let date2Formatter = DateFormatter()
date2Formatter.dateFormat = "yyyy-MM-dd hh:mm:ss"
date2Formatter.timeZone = TimeZone(abbreviation: "UTC")!
let date1 = Date(timeIntervalSince1970: date1Timestamp)
let date2 = date2Formatter.date(from: date2Str)!
// Here we make assumption that date2 is later then date1
// So, later goes first if you don't want negative results
// or you can use abs if you want
let differenceComponents = Calendar.current.dateComponents([.minute, .hour, .day], from: date2, to: date1)
print("Date 1: \(date1)")
print("Date 2: \(date2)")
print("Difference is: \(differenceComponents)")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment