'Get build date and time in Swift

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?



Solution 1:[1]

You can use #line, #column, and #function.


Original answer:

Create a new Objective-C file in your project, and when Xcode asks, say yes to creating the bridging header.

In this new Objective-C file, add the following the the .h file:

NSString *compileDate();
NSString *compileTime();

And in the .m implement these functions:

NSString *compileDate() {
    return [NSString stringWithUTF8String:__DATE__];
}

NSString *compileTime() {
    return [NSString stringWithUTF8String:__TIME__];
}

Now go to the bridging header and import the .h we created.

Now back to any of your Swift files:

println(compileDate() + ", " + compileTime())

Solution 2:[2]

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

Solution 3:[3]

Swift 5 version of Alain T's answer:

var buildDate: Date {
    if let infoPath = Bundle.main.path(forResource: "Info", ofType: "plist"),
        let infoAttr = try? FileManager.default.attributesOfItem(atPath: infoPath),
        let infoDate = infoAttr[.modificationDate] as? Date {
        return infoDate
    }
    return Date()
}

Solution 4:[4]

A slight variation on previous answers, checking the executable creation date instead. This seems to work on macOS too (tested with a Catalyst app).

/// Returns the build date of the app.
public static var buildDate: Date
{
    if let executablePath = Bundle.main.executablePath,
        let attributes = try? FileManager.default.attributesOfItem(atPath: executablePath),
        let date = attributes[.creationDate] as? Date
    {
        return date
    }
    return Date()
}

Solution 5:[5]

All the older answers here are not good, as they do not provide a steady and reliable way to get the actual build date. For instance, getting the file date of a file inside the app is not good because the file date could change without invalidating the app's code signature.

The official build date is added by Xcode to the app's Info.plist – that's the one you should be using.

E.g, with this code (sorry, it's in ObjC, but transscribing it to Swift shouldn't be so hard):

+ (NSDate *)buildDate {
    static NSDate *result = nil;
    if (result == nil) { 
        NSDictionary *infoDictionary = NSBundle.mainBundle.infoDictionary;
        NSString *s = [infoDictionary valueForKey:@"BuildDateString"];
        NSISO8601DateFormatter *formatter = [[NSISO8601DateFormatter alloc] init];
        NSDate *d = [formatter dateFromString:s];
        result = d;
    }
    return result;
}

And this is the script you'll have to run from your project's Build Phases in order to add the BuildDateString to your Info.plist:

#!/bin/sh
infoplist="$BUILT_PRODUCTS_DIR/$INFOPLIST_PATH"
builddate=`date +%Y-%m-%dT%H:%M:%S%z`
if [[ -n "$builddate" ]]; then
    # if BuildDateString doesn't exist, add it
    /usr/libexec/PlistBuddy -c "Add :BuildDateString string $builddate" "${infoplist}"
    # and if BuildDateString already existed, update it
    /usr/libexec/PlistBuddy -c "Set :BuildDateString $builddate" "${infoplist}"
fi

Solution 6:[6]

A Tamperproof Approach:

  1. Add a new Run Script build phase to your app and MAKE SURE it is set to run before the Compile Sources phase.

  2. Add this as the code in that script:

#!/bin/bash

timestamp=$(date +%s)
echo "import Foundation;let appBuildDate: Date = Date(timeIntervalSince1970: $timestamp)" > ${PROJECT_DIR}/Path/To/Some/BuildTimestamp.swift
  1. Create the file BuildTimestamp.swift at some path in your project, then make sure the output path in the script above matches where that file exists, relative to the project's root folder.

  2. You now have a global appBuildDate that can be used anywhere in your project. (Build the project once before using the variable so that the script creates it in the file you specified.)

  3. Optional: if you'd like the date to update in incremental builds, be sure to uncheck the "based on dependency analysis" checkbox in the Run Script phase you created.

Advantages:

  1. It's automatic.

  2. It can't be affected by users changing the modification/creation date of various files in the app bundle (a concern on macOS).

  3. It doesn't need the old __TIME__ and __DATE__ from C.

  4. It's already a Date and ready to be used, as-is.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3 Brian Hong
Solution 4 Luke Rogers
Solution 5
Solution 6 Bryan