find the creation date of a file in swift

You can find the creation date of a file in Swift using the FileManager API. Here's an example:

main.swift
let fileManager = FileManager.default
let filePath = "path/to/your/file.txt"

do {
    let fileAttributes = try fileManager.attributesOfItem(atPath: filePath)
    if let creationDate = fileAttributes[.creationDate] as? NSDate {
        print("File was created on \(creationDate)")
    }
} catch {
    print("Error getting file attributes: \(error)")
}
352 chars
12 lines

In the example above, we first create an instance of the FileManager class. Then, we define the path to the file whose creation date we want to find.

Next, we use a do-catch block to attempt to get the attributes of the file at the specified path using the attributesOfItem(atPath:) method of the FileManager class.

If we're successful in retrieving the attributes of the file, we extract the creation date using the .creationDate key, and cast it to an NSDate object. We then print the creation date to the console.

If there's an error while retrieving the file attributes, we catch the error and print it to the console.

gistlibby LogSnag