【发布时间】:2020-05-21 08:17:22
【问题描述】:
我正在尝试使用 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
}
【问题讨论】:
-
如果数据只有几个字节,你能打印数据的各个字节吗?这样我们可以尝试找出数据的格式。也就是说,您可以随时尝试
NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data) as! Date。 -
查看this 文章。基本上,您可以使用
JSONDecder并将其dateDecodingStrategy设置为适当的值。 -
@Sweeper:你可以在
value : <b9b6c35e 00000000 abd73225 00000000>看到各个字节 -
@MartinR 这是一种令人困惑的字节写入方式……他们为什么要这样分组?我完全认为这是某种地址...
-
@Sweeper:这就是
NSData在 Objective-C 中的打印方式。我假设实际值是 NSData 但桥接到 Data for Swift。 – 地址将有 8 个字节,而不是 16 个。