我正在尝试使用NSFileManager获取文件的上次使用日期,我正在以NSData格式获取日期,但我不确定如何将数据转换为日期。
我从NSFileManager获得的值低于
key : "com.apple.lastuseddate#PS"
value : <b9b6c35e 00000000 abd73225 00000000>
请让我知道如何将上述数据值转换为日期。
我使用下面的函数将数据转换为日期,但是我得到的值完全错误。
func dataToDate(data:Data) -> Date{ let components = NSDateComponents() let bytes = [uint8](data) components.year = Int(bytes[0] | bytes[1] << 8) components.month = Int(bytes[2]) components.day = Int(bytes[3]) components.hour = Int(bytes[4]) components.minute = Int(bytes[5]) components.second = Int(bytes[6]) let calendar = NSCalendar.current return calendar.date(from: components as DateComponents)! }
编辑: @Martin R,下面是我用来获取数据的代码。
var attributes:[FileAttributeKey : Any]?
do{
attributes = try FileManager.default.attributesOfItem(atPath: url.path)
}catch{
print("Issue getting attributes of file")
}
if let extendedAttr = attributes![FileAttributeKey(rawValue: "NSFileExtendedAttributes")] as? [String : Any]{
let data = extendedAttr["com.apple.lastuseddate#PS"] as? Data
}
答案 0 :(得分:2)
必要的信息可以在Apple开发者论坛的Data to different types ?中找到。
首先请注意,依靠未记录的扩展属性是不安全的。获得相同结果的更好方法是从NSMetadataItemLastUsedDateKey
中检索NSMetadataItem
:
if let date = NSMetadataItem(url: url)?.value(forAttribute: NSMetadataItemLastUsedDateKey) as? Date {
print(date)
}
但要回答您的实际问题:该扩展属性包含一个
UNIX struct timespec
(比较<time.h>
)值。这是用于st_atimespec
和struct stat
的其他成员的类型(又是fstat()
和类似系统调用使用的类型)。
您必须将数据复制到timespec
值中,从tv_sec
和tv_nsec
成员中计算秒数,然后从Unix时代。
Date
示例(您的数据):
func dataToDate(data: Data) -> Date {
var ts = timespec()
precondition(data.count >= MemoryLayout.size(ofValue: ts))
_ = withUnsafeMutableBytes(of: &ts, { lastuseddata.copyBytes(to: $0)} )
let seconds = TimeInterval(ts.tv_sec) + TimeInterval(ts.tv_nsec)/TimeInterval(NSEC_PER_SEC)
return Date(timeIntervalSince1970: seconds)
}