【问题标题】:iOS: How do you find the creation date of a file?iOS:如何找到文件的创建日期?
【发布时间】:2011-01-07 17:07:48
【问题描述】:

我正在尝试查找文件的创建日期(不是修改日期)。

创建日期似乎不在文件的属性中,但修改日期在。

我正在使用此代码..

NSFileManager* fm = [NSFileManager defaultManager];

NSString* path = [PathHelpers pathInDocumentsFolderWithFilename:FILE_NAME];
NSDictionary* attrs = [fm attributesOfItemAtPath:path error:nil];

if (attrs != nil) {
    return (NSDate*)[attrs objectForKey: NSFileCreationDate];
} else {
    return nil;
}

这总是返回 nil。在调试器中键入 'po attrs' 以获取 NSDictionary 中的键/值对列表返回以下内容..

NSFileGroupOwnerAccountID = 20;
NSFileGroupOwnerAccountName = 员工;
NSFileModificationDate = 2010-01-21 11:47:55 +0000;
NSFileOwnerAccountID = 501;
NSFileOwnerAccountName = 本;
NSFilePosixPermissions = 420;
NSFileReferenceCount = 1;
NSFileSize = 338;
NSFileSystemFileNumber = 2234;
NSFileSystemNumber = 42553324;
NSFileType = NSFileTypeRegular;

没有创建日期.. bah..

有谁知道获取创建日期的另一种方法,还是它在 iOS 中不存在?

【问题讨论】:

  • 请注意,我显示的跟踪来自 iphone 模拟器。但是,我在真实设备上遇到了同样的问题 - 未列出创建日期。
  • 文档将 NSFileCreationDate 列为返回值,因此您可能想向 Apple 提交错误。这听起来确实不像预期的那样。

标签: ios file date nsfilemanager


【解决方案1】:

这段代码实际上将好的创建日期返回给我:

NSFileManager* fm = [NSFileManager defaultManager];
NSDictionary* attrs = [fm attributesOfItemAtPath:path error:nil];

if (attrs != nil) {
    NSDate *date = (NSDate*)[attrs objectForKey: NSFileCreationDate];
    NSLog(@"Date Created: %@", [date description]);
} 
else {
    NSLog(@"Not found");
}

您是在应用程序内创建文件吗?也许这就是问题所在。

【讨论】:

  • 抱歉问这个愚蠢的问题... "attributesOfItemAtPath:path" 如何初始化这个 "path" 变量。假设我在项目的根目录中放置了一个名为“icon_57.png”的图像?
  • @jeet.chanchawat 这是一个 Swift 实现......应该很容易获得 ObjC let documentsDirectoryString = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] return documentsDirectory.stringByAppendingPathComponent("icon_57.png")的语法
【解决方案2】:

NSDictionary 中有一个特殊的消息fileCreationDate。以下对我有用:

目标-C:

NSDate *date = [attrs fileCreationDate];

斯威夫特:

let attrs = try NSFileManager.defaultManager().attributesOfItemAtPath(path) as NSDictionary
attrs.fileCreationDate()

【讨论】:

  • swift 版本运行良好,但在 swift 5 中(至少)没有称为 attrs.fileCreationDate() 的方法,而是我使用了 attrs[.creationDate] as? Date ...如果你想知道
【解决方案3】:

更新了 Swift 4 的答案以提取修改 (.modifiedDate) 或创建 (.creationDate) 日期:

let file: URL = ...
if let attributes = try? FileManager.default.attributesOfItem(atPath: file.path) as [FileAttributeKey: Any],
    let creationDate = attributes[FileAttributeKey.creationDate] as? Date {
    print(creationDate)
    }
  1. 使用您预先通过 URL 提供的文件,它将请求其属性。如果成功,则返回 [FileAttributeKey: Any] 字典
  2. 使用第 1 步中的字典,然后提取创建日期(或根据需要进行修改)并使用条件展开,如果成功则将其分配给日期
  3. 假设前两个步骤成功,您现在有了一个可以使用的日期

【讨论】:

    【解决方案4】:

    Swift 2.0 版本:

    do {
        let fileAttributes = try NSFileManager.defaultManager().attributesOfItemAtPath(YOURPATH)
        let creationDate = fileAttributes[NSFileCreationDate] as? NSDate
        let modificationDate = fileAttributes[NSFileModificationDate] as? NSDate
        print("creation date of file is", creationDate)
        print("modification date of file is", modificationDate)
    }catch let error as NSError {
        print("file not found:", error)
    }
    

    【讨论】:

      【解决方案5】:

      在 Swift 4 中,如果您想知道 DocumentsDirectory 中特定文件的文件创建日期,可以使用此方法

      func getfileCreatedDate(theFile: String) -> Date {
      
              var theCreationDate = Date()
              do{
                  let aFileAttributes = try FileManager.default.attributesOfItem(atPath: theFile) as [FileAttributeKey:Any]
                  theCreationDate = aFileAttributes[FileAttributeKey.creationDate] as! Date
      
              } catch let theError as Error{
                  print("file not found \(theError)")
              }
              return theCreationDate
          }
      

      【讨论】:

        【解决方案6】:

        在 Swift 5 中:

        let date = (try? FileManager.default.attributesOfItem(atPath: path))?[.creationDate] as? Date
        

        【讨论】:

          【解决方案7】:
            NSDate *creationDate = nil;
            if ([fileManager fileExistsAtPath:filePath]) {
                 NSDictionary *attributes = [fileManager attributesOfItemAtPath:filePath error:nil];
                 creationDate = attributes[NSFileCreationDate];
            }
          

          它的here

          【讨论】:

            【解决方案8】:

            Swift 3 版本代码:

            do {
                    let fileAttributes = try FileManager.default.attributesOfItem(atPath: yourPathString)
                    let modificationDate = fileAttributes[FileAttributeKey.modificationDate] as! Date
                    print("Modification date: ", modificationDate)
                } catch let error {
                    print("Error getting file modification attribute date: \(error.localizedDescription)")
                }
            

            【讨论】:

            • 如果你也能解释你的答案,不胜感激。
            • 如果您希望文件创建日期符合 OP,请使用 FileAttributeKey.creationDate。
            【解决方案9】:

            你可以使用fstat64 来获取返回结构的st_birthtimespec 成员吗?您需要为该文件创建一个 C 文件句柄并将 timespec 值转换为 NSDate,但这总比没有好。

            【讨论】:

            • 不,您不应该使用 fstat64,因为据我所知 iPhone OS 还不是 64 位。不幸的是,在 32 位模式下,struct timespec st_birthtimespec 在 struct stat 中不可用。这就是为什么 [attrs fileCreationDate] 返回的 NSDate 对象在 iPhone 3.1.2 上始终为 nil 的原因,其中 attrs 是包含文件属性的 NSDictionary。
            • 谢谢大家。看起来我只需要记住文件的创建时间并将其存储在 NSUserDefaults 中。
            【解决方案10】:

            斯威夫特 5

            let url: URL = ....
            let attributes = try? FileManager.default.attributesOfItem(atPath: url.path)
            if let date = attributes?[.modificationDate] {
               print("File Modification date is %@", date)
            }
            if let date = attributes?[.creationDate] {
               print("File Creation date is %@", date)
            }
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2011-12-20
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2013-05-08
              • 1970-01-01
              • 2011-06-27
              相关资源
              最近更新 更多