Swift - 基于时间的 UUID - 如何对它们进行排序
Swift - time based UUID - how to sort them
我正在为项目创建和使用时基 UUID。我正在使用这个功能:
class func timeBasedUUID() -> NSUUID {
let uuidSize = sizeof(uuid_t)
let uuidPointer = UnsafeMutablePointer<UInt8>.alloc(uuidSize)
uuid_generate_time(uuidPointer)
let uuid = NSUUID(UUIDBytes: uuidPointer)
uuidPointer.dealloc(uuidSize)
return uuid
}
现在我想知道如何将它们从最旧到最新排序。我正在考虑比较字符串,但它是正确的吗?因为我不这么认为。
UUID 没有 "oldest" 或 "newest" 组件。确实 uuid_generate_time
使用时间来帮助保证 唯一性 ,但它并不是一种实际记录时间的方式。不要试图以这种方式滥用它。如果你知道你需要按日期对项目进行排序,你需要给他们一些额外的信息,例如。时间戳。
从 swift 中的 UUIDv1 解码时间戳:
extension UUID {
static func timeBasedUUID() -> UUID? {
let uuidSize = MemoryLayout<uuid_t>.size
let uuidPointer = UnsafeMutablePointer<UInt8>.allocate(capacity: uuidSize)
uuid_generate_time(uuidPointer)
let uuid = uuidPointer.withMemoryRebound(to: uuid_t.self, capacity: 1) {
return [=10=].pointee
}
uuidPointer.deallocate()
return UUID(uuid: uuid)
}
var timestamp: TimeInterval {
let components = uuidString.split(separator: "-")
assert(components.count == 5)
let hex = String(components[2].dropFirst()) + components[1] + components[0]
// 100-nanoseconds intervals
let interval = Int(hex, radix: 16)!
let seconds = TimeInterval(interval / 10000000)
// -12219292800 relative seconds to 1970
return seconds - 12219292800
}
}
参考文献:
how do i get the date/time back from a UUID type 1
我正在为项目创建和使用时基 UUID。我正在使用这个功能:
class func timeBasedUUID() -> NSUUID {
let uuidSize = sizeof(uuid_t)
let uuidPointer = UnsafeMutablePointer<UInt8>.alloc(uuidSize)
uuid_generate_time(uuidPointer)
let uuid = NSUUID(UUIDBytes: uuidPointer)
uuidPointer.dealloc(uuidSize)
return uuid
}
现在我想知道如何将它们从最旧到最新排序。我正在考虑比较字符串,但它是正确的吗?因为我不这么认为。
UUID 没有 "oldest" 或 "newest" 组件。确实 uuid_generate_time
使用时间来帮助保证 唯一性 ,但它并不是一种实际记录时间的方式。不要试图以这种方式滥用它。如果你知道你需要按日期对项目进行排序,你需要给他们一些额外的信息,例如。时间戳。
从 swift 中的 UUIDv1 解码时间戳:
extension UUID {
static func timeBasedUUID() -> UUID? {
let uuidSize = MemoryLayout<uuid_t>.size
let uuidPointer = UnsafeMutablePointer<UInt8>.allocate(capacity: uuidSize)
uuid_generate_time(uuidPointer)
let uuid = uuidPointer.withMemoryRebound(to: uuid_t.self, capacity: 1) {
return [=10=].pointee
}
uuidPointer.deallocate()
return UUID(uuid: uuid)
}
var timestamp: TimeInterval {
let components = uuidString.split(separator: "-")
assert(components.count == 5)
let hex = String(components[2].dropFirst()) + components[1] + components[0]
// 100-nanoseconds intervals
let interval = Int(hex, radix: 16)!
let seconds = TimeInterval(interval / 10000000)
// -12219292800 relative seconds to 1970
return seconds - 12219292800
}
}
参考文献:
how do i get the date/time back from a UUID type 1