Get build date and time in Swift

David Potter picture David Potter · Nov 8, 2014 · Viewed 7.1k times · Source

I'm using __DATE__ and __TIME__ in Objective-C to get the build date and time of my app. I can't find a way to get this information in Swift. Is it possible?

Answer

Alain T. picture Alain T. · Jul 17, 2016

You can get the build date and time without reverting to objective-C. When the app is built, the Info.plist file placed in the bundle is always created from the one in your project. So the creation date of that file matches the build date and time. You can always read files in your app's bundle and get their attributes. So you can get the build date in Swift by accessing its Info.plist file attributes:

 var buildDate:NSDate 
 {
     if let infoPath = NSBundle.mainBundle().pathForResource("Info.plist", ofType: nil),
        let infoAttr = try? NSFileManager.defaultManager().attributesOfItemAtPath(infoPath),
        let infoDate = infoAttr["NSFileCreationDate"] as? NSDate
     { return infoDate }
     return NSDate()
 }

Note: this is the post that got me to use the bridging header when I initially had this problem. I found this "Swiftier" solution since then so I thought I'd share it for future reference.

[EDIT] added compileDate variable to get the latest compilation date even when not doing a full build. This only has meaning during development since you're going to have to do a full build to release the application on the app store but it may still be of some use. It works the same way but uses the bundled file that contains the actual code instead of the Info.plist file.

var compileDate:Date
{
    let bundleName = Bundle.main.infoDictionary!["CFBundleName"] as? String ?? "Info.plist"
    if let infoPath = Bundle.main.path(forResource: bundleName, ofType: nil),
       let infoAttr = try? FileManager.default.attributesOfItem(atPath: infoPath),
       let infoDate = infoAttr[FileAttributeKey.creationDate] as? Date
    { return infoDate }
    return Date()
}