How to write build time stamp into apk

If you use Gradle, you can add buildConfigField with timestamp updated at build time.

android {
    defaultConfig {
        buildConfigField "long", "TIMESTAMP", System.currentTimeMillis() + "L"
    }
}

Then read it at runtime.

Date buildDate = new Date(BuildConfig.TIMESTAMP);

Method which checks date of last modification of classes.dex, this means last time when your app's code was built:

  try{
     ApplicationInfo ai = getPackageManager().getApplicationInfo(getPackageName(), 0);
     ZipFile zf = new ZipFile(ai.sourceDir);
     ZipEntry ze = zf.getEntry("classes.dex");
     long time = ze.getTime();
     String s = SimpleDateFormat.getInstance().format(new java.util.Date(time));
     zf.close();
  }catch(Exception e){
  }

Tested, and works fine, even if app is installed on SD card.


Since API version 9 there's:

PackageInfo.lastUpdateTime

The time at which the app was last updated.

try {
    PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
    //TODO use packageInfo.lastUpdateTime
} catch (PackageManager.NameNotFoundException e) {
    e.printStackTrace();
}

On lower API versions you must make build time yourself. For example putting a file into assets folder containing the date. Or using __ DATE__ macro in native code. Or checking date when your classes.dex was built (date of file in your APK).


Edit: My answer does not work anymore since option keepTimestampsInApk was removed. Working in 2020 is https://stackoverflow.com/a/26372474/6937282 (also https://stackoverflow.com/a/22649533/6937282 for more details)

Original answer:

A hint for solution "last modification time of classes.dex file" an newer AndroidStudio versions: In default config the timestamp is not written anymore to files in apk file. Timestamp is always "Nov 30 1979".

You can change this behavior by adding this line to file

%userdir%/.gradle/gradle.properties (create if not existing)

android.keepTimestampsInApk = true

See Issue 220039

(Must be in userdir, gradle.properties in project build dir seems not to work)