获取文件属性主要用到FileManager的实例方法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)")
}
发现以上时间为GMT时间,需要转换为本地时间。附上将转换时区的方法,将以上方法替换为:
//将GMT时间转换为本地时间
//获取本地时区及与GMT的时间间隔
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)")
}