Skip to content

Instantly share code, notes, and snippets.

@Frizlab
Created December 2, 2016 13:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Frizlab/eee2ce3f1b6dc291c6744af53fca071f to your computer and use it in GitHub Desktop.
Save Frizlab/eee2ce3f1b6dc291c6744af53fca071f to your computer and use it in GitHub Desktop.
Date from UUID in Swift
/* From https://www.famkruithof.net/guid-uuid-make.html
 * and https://www.famkruithof.net/guid-uuid-timebased.html */
extension UUID {
var isTimeUUID: Bool {
return (uuid.8 & 0xC0) == 0x80 /* Variant is the one we expect */ && (uuid.6 & 0xF0) == 0x10 /* Time-based version of the variant */
}
var generationDate: Date? {
guard isTimeUUID else {return nil}
let dateInt: UInt64 = (
UInt64(uuid.3) * 0x1 +
UInt64(uuid.2) * 0x100 +
UInt64(uuid.1) * 0x10000 +
UInt64(uuid.0) * 0x1000000 +
UInt64(uuid.5) * 0x100000000 +
UInt64(uuid.4) * 0x10000000000 +
UInt64(uuid.7) * 0x1000000000000 +
UInt64(uuid.6 & 0x0F) * 0x100000000000000
)
/* The solution below works too, but on little-endian architectures only. */
// var dateInt: UInt64 = 0
// withUnsafeMutableBytes(of: &dateInt) { bytes in
// bytes[7] = uuid.6 & 0x0F
// bytes[6] = uuid.7
// bytes[5] = uuid.4
// bytes[4] = uuid.5
// bytes[3] = uuid.0
// bytes[2] = uuid.1
// bytes[1] = uuid.2
// bytes[0] = uuid.3
// }
return Date(timeInterval: TimeInterval(dateInt)/10000000, since: Date(timeIntervalSince1970: TimeInterval(-12219292800)))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment