43

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..

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;

No creation date.. bah..

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

Ben Clayton
  • 80,996
  • 26
  • 120
  • 129
  • Note that the trace i've shown is from the iphone simulator. I get the same issue on a real device however - creation date isn't listed. – Ben Clayton Jan 21 '10 at 12:09
  • 1
    The documentation lists NSFileCreationDate as a returned value, s o you might want to file a bug with Apple. It certainly sounds like this isn't behaving as expected. – Jeff Kelley Jan 21 '10 at 12:39

10 Answers10

72

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.

Oriol Nieto
  • 5,409
  • 6
  • 32
  • 38
  • Sorry to ask this silly question... "attributesOfItemAtPath:path" How to initialise this "path" variable. suppose I am having a image named "icon_57.png" placed in the root of project ? – jeet.chanchawat Jun 10 '14 at 12:34
  • 1
    @jeet.chanchawat here's a Swift implementation... should be easy enough to get the syntax for ObjC `let documentsDirectoryString = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] return documentsDirectory.stringByAppendingPathComponent("icon_57.png")` – Magoo Jan 28 '16 at 11:34
21

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

Objective-C:

NSDate *date = [attrs fileCreationDate];

Swift:

let attrs = try NSFileManager.defaultManager().attributesOfItemAtPath(path) as NSDictionary
attrs.fileCreationDate()
ricardopereira
  • 11,118
  • 5
  • 63
  • 81
Ridcully
  • 23,362
  • 7
  • 71
  • 86
  • 2
    The swift version works fine but in swift 5 (at least) there is no method called `attrs.fileCreationDate()`, instead I used `attrs[.creationDate] as? Date` ...if you are wondering – lcpr_phoenix May 21 '21 at 16:38
11

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

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
CodeBender
  • 35,668
  • 12
  • 125
  • 132
9

Swift 2.0 version:

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)
}
Sam
  • 5,375
  • 2
  • 45
  • 54
9

In Swift 5:

let date = (try? FileManager.default.attributesOfItem(atPath: path))?[.creationDate] as? Date
mishimay
  • 4,237
  • 1
  • 27
  • 23
7

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

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
    }
Naishta
  • 11,885
  • 4
  • 72
  • 54
3
  NSDate *creationDate = nil;
  if ([fileManager fileExistsAtPath:filePath]) {
       NSDictionary *attributes = [fileManager attributesOfItemAtPath:filePath error:nil];
       creationDate = attributes[NSFileCreationDate];
  }

Its here

Govind
  • 2,337
  • 33
  • 43
3

Swift 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)
}
Ankur Lahiry
  • 2,253
  • 1
  • 15
  • 25
2

Swift 3 version code:

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)")
    }
mriaz0011
  • 1,887
  • 23
  • 11
1

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

Jeff Kelley
  • 19,021
  • 6
  • 70
  • 80
  • 1
    No, you should not be able to use fstat64 owing to the fact that, to the best of my knowledge iPhone OS is not yet 64 bits. Unfortunately, in 32 bits mode, the struct timespec st_birthtimespec is NOT available in struct stat. This is the reason why the NSDate object returned by [attrs fileCreationDate] will be always nil on the iPhone as of 3.1.2, where attrs is the NSDictionary containing the file attributes. – Massimo Cafaro Jan 21 '10 at 12:52
  • Thanks guys. Looks like I'll just have to remember when the file was created and store it in NSUserDefaults. – Ben Clayton Jan 21 '10 at 13:12