将数据转换为日期

问题描述 投票:1回答:1

我正在尝试使用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
}
swift macos nsdate nsdata
1个回答
2
投票

可以在Apple Developer Forum的Data to different types ?中找到必要的信息。

首先请注意,依靠未记录的扩展属性是不安全的。获得相同结果的更好方法是从NSMetadataItemLastUsedDateKey中检索NSMetadataItem

if let date = NSMetadataItem(url: url)?.value(forAttribute: NSMetadataItemLastUsedDateKey) as? Date {
    print(date)
}

但是要回答您的实际问题:该扩展属性包含一个 UNIX struct timespec(比较<time.h>)值。这是用于<time.h>st_atimespec的其他成员的类型(又是用于struct stat和类似系统调用的类型)。

您必须将数据复制到fstat()值,从timespectv_sec成员中计算秒数,然后从Unix时代以来的秒数创建一个tv_nsec

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)
}
© www.soinside.com 2019 - 2024. All rights reserved.