iOS:如何找到文件的创建日期?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2108953/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 16:48:55  来源:igfitidea点击:

iOS: How do you find the creation date of a file?

iosfiledatensfilemanager

提问by Ben Clayton

I'm trying to find the creation date (NOT modification date) of a file.

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

Creation date doesn't appear to be in the attributes of a file, though modified date is.

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

I'm using this code..

我正在使用此代码..

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;
}

This always returns nil. Typing 'po attrs' into the debugger to get the list of key/value pairs in the NSDictionary returns the following..

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

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

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

No creation date.. bah..

没有创建日期..呸..

Anyone know another way of getting the creation date or does it just not exist in iOS?

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

回答by Oriol Nieto

This code actually returns the good creation date to me:

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

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");
}

Are you creating the file inside the App? Maybe that's where the problem is.

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

回答by Ridcully

There is a special message fileCreationDatefor that in NSDictionary. The following works for me:

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

Objective-C:

目标-C:

NSDate *date = [attrs fileCreationDate];

Swift:

迅速:

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

回答by Sam

Swift 2.0 version:

斯威夫特 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)
}

回答by Naishta

In Swift 4, if you want to know the file created date for a specific file in DocumentsDirectory, you can use this method

在 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
    }

回答by CodeBender

Updated answer for Swift 4to pull out the modified (.modifiedDate) or creation (.creationDate) date:

更新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. Using a file that you provide in advance via a URL, it will request its attributes. If successful a dictionary of [FileAttributeKey: Any] is returned
  2. Using the dictionary from step 1, it then pulls out the creation date (or modified if you prefer) and using the conditional unwrap, assigns it to a date if successful
  3. Assuming the first two steps are successful, you now have a date that you can work with
  1. 使用您通过 URL 预先提供的文件,它将请求其属性。如果成功,则返回 [FileAttributeKey: Any] 的字典
  2. 使用步骤 1 中的字典,然后提取创建日期(或根据您的喜好进行修改)并使用条件解包,如果成功则将其分配给日期
  3. 假设前两个步骤成功,您现在有一个可以使用的日期

回答by Govind

  NSDate *creationDate = nil;
  if ([fileManager fileExistsAtPath:filePath]) {
       NSDictionary *attributes = [fileManager attributesOfItemAtPath:filePath error:nil];
       creationDate = attributes[NSFileCreationDate];
  }

Its here

在这里

回答by mishimay

In Swift 5:

在 Swift 5 中:

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

回答by mriaz0011

Swift 3 version code:

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)")
    }

回答by Jeff Kelley

Can you use fstat64to get the st_birthtimespecmember of the returned struct? You'll need to create a C file handle for the file and convert the timespecvalue into an NSDate, but that's better than nothing.

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