wyskoj
wyskoj

Reputation: 408

Get build time with Gradle Kotlin DSL

In my Gradle script's build task, I want to get the current timestamp whenever I build my project and save it to a file in my project's resource directory. If I understand correctly, I should be able to call Java methods to achieve this, something like (in Kotlin):

val timestamp = SimpleDateFormat("yyyy-MM-dd-HH:mm:ss").format(Date())

Attempting to import my script into IntelliJ fails with unresolved reference errors (SimpleDateFormat and Date).

Using the fully qualified name does not work either (java.util.Date); IntelliJ shows that it tries to treat java as the java plugin.

My build.gradle.kts looks like this:

plugins {
    `java-library`
    kotlin("jvm") version "1.6.10"
    java
    idea
    application
    ... other plugins ...
    
}

tasks.build {
    val timestamp = SimpleDateFormat("MM-dd-yyyy_hh-mm").format(Date())
}

... other configuration ...

How can I properly use those references? Am I missing a specific plugin, or do I need to be taking a whole different approach?

Upvotes: 8

Views: 4327

Answers (1)

Endzeit
Endzeit

Reputation: 5514

Have you tried adding an import statement to the top of your build.gradle.kts file?

Most likely java refers to the identically named task, because you're inside the tasks scope.

import java.util.Date
import java.text.SimpleDateFormat

plugins {
   ...
}

tasks.build {
    val timestamp = SimpleDateFormat("MM-dd-yyyy_hh-mm").format(Date())
}

... other configuration ...

Instead of using the java.util.Date class, I recommend taking a look at the newer java.time.Instant class instead.

Upvotes: 13

Related Questions