Timestamp in Kotlin

Mattepuffo's logo
Timestamp in Kotlin

Timestamp in Kotlin

Oggi vediamo due esempi su come ottenere il timestamp in Kotlin.

Nel primo esempio vediamo come ottenerlo prendendo direttamente data e orario e attuale del sistema.

Nel secondo esempio invece partiremo da una stringa che contiene la data.

Ecco il codice:

import java.text.DateFormat
import java.text.SimpleDateFormat
import java.util.*

fun main(args: Array<String>) {
    val currentTimestamp = System.currentTimeMillis()
    println(currentTimestamp)

    val strData = "20/10/2021"
    val formatter: DateFormat = SimpleDateFormat("dd/MM/yyyy")
    val date: Date = formatter.parse(strData) as Date
    println(date.getTime())
}

Come potete vedere nel secondo esempio, dobbiamo passare per SimpleDateFormat.

Così possiamo formattare la stringa e trasformarlo in un oggetto Date.

Ovviamente qui non abbiamo orario, quindi il timestamp non sarà corretto al 100%.

Enjoy!


Condividi

Commentami!