獲取文件屬性主要用到FileManager的實(shí)例方法attributesOfItem(atPath:)
let filePath = "xxx"
do {
let fileAttributes = try FileManager.default.attributesOfItem(atPath: filePath)
if let fileSize:NSNumber = fileAttributes[FileAttributeKey.size] as! NSNumber? {
print("File Size: \(fileSize.uint32Value)")
}
if let ownerName = fileAttributes[FileAttributeKey.ownerAccountName] {
print("File Owner: \(ownerName)")
}
if let creationDate = fileAttributes[FileAttributeKey.creationDate] {
print("File Creation Date: \(creationDate)")
}
if let modificationDate = fileAttributes[FileAttributeKey.modificationDate] {
print("File Modification Date: \(modificationDate)")
}
} catch let error as NSError {
print("Get attributes errer: \(error)")
}
發(fā)現(xiàn)以上時(shí)間為GMT時(shí)間,需要轉(zhuǎn)換為本地時(shí)間。附上將轉(zhuǎn)換時(shí)區(qū)的方法,將以上方法替換為:
//將GMT時(shí)間轉(zhuǎn)換為本地時(shí)間
//獲取本地時(shí)區(qū)及與GMT的時(shí)間間隔
let timeZone = NSTimeZone.system
let interval: TimeInterval = TimeInterval(timeZone.secondsFromGMT())
if let creationDate = fileAttributes[FileAttributeKey.creationDate] {
let localCreateDate = (creationDate as! NSDate).addingTimeInterval(interval)
print("File Creation Date: \(localCreateDate)")
}
if let modificationDate = fileAttributes[FileAttributeKey.modificationDate] {
let localModDate = (modificationDate as! NSDate).addingTimeInterval(interval)
print("File Modification Date: \(localModDate)")
}