Kotlin convert TimeStamp to DateTime

Viewed 78739

I'm trying to find out how I can convert timestamp to datetime in Kotlin, this is very simple in Java but I cant find any equivalent of it in Kotlin.

For example: epoch timestamp (seconds since 1970-01-01) 1510500494 ==> DateTime object 2017-11-12 18:28:14.

Is there any solution for this in Kotlin or do I have to use Java syntax in Kotlin? Please give me a simple sample to show how I can resolve this problem. Thanks in advance.

this link is not an answer to my question

13 Answers
private fun getDateTime(s: String): String? {
    try {
        val sdf = SimpleDateFormat("MM/dd/yyyy")
        val netDate = Date(Long.parseLong(s) * 1000)
        return sdf.format(netDate)
    } catch (e: Exception) {
        return e.toString()
    }
}

Although it's Kotlin, you still have to use the Java API. An example for Java 8+ APIs converting the value 1510500494 which you mentioned in the question comments:

import java.time.*

val dt = Instant.ofEpochSecond(1510500494)
                .atZone(ZoneId.systemDefault())
                .toLocalDateTime()
class DateTest {

    private val simpleDateFormat = SimpleDateFormat("dd MMMM yyyy, HH:mm:ss", Locale.ENGLISH)

    @Test
    fun testDate() {
        val time = 1560507488
        println(getDateString(time)) // 14 June 2019, 13:18:08
    }

    private fun getDateString(time: Long) : String = simpleDateFormat.format(time * 1000L)

    private fun getDateString(time: Int) : String = simpleDateFormat.format(time * 1000L)

}

Notice that we multiply by 1000L, not 1000. In case you have an integer number (1560507488) muliplied by 1000, you will get a wrong result: 17 January 1970, 17:25:59.

Here is a solution in Kotlin

fun getShortDate(ts:Long?):String{
    if(ts == null) return ""
    //Get instance of calendar
    val calendar = Calendar.getInstance(Locale.getDefault())
    //get current date from ts
    calendar.timeInMillis = ts
    //return formatted date 
    return android.text.format.DateFormat.format("E, dd MMM yyyy", calendar).toString()
}
val sdf = SimpleDateFormat("dd/MM/yy hh:mm a") 
val netDate = Date(item.timestamp) 
val date =sdf.format(netDate)

Log.e("Tag","Formatted Date"+date)

"sdf" is variable "SimpleDateFormat" of where we can set format of date as we want.

"netDate" is variable of Date. In Date we can sending timestamp values and printing that Date by SimpleDateFormat by using sdf.format(netDate).

This worked for me - takes a Long

    import java.time.*

    private fun getDateTimeFromEpocLongOfSeconds(epoc: Long): String? {
        try {
            val netDate = Date(epoc*1000)
            return netDate.toString()
        } catch (e: Exception) {
            return e.toString()
        }
   }
@SuppressLint("SimpleDateFormat")
fun dateFormatter(milliseconds: String): String {
    return SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(Date(milliseconds.toLong())).toString()
}

This is a improved version existing answers (Sahil's and Javier's)

val stamp = Timestamp(System.currentTimeMillis()) // from java.sql.timestamp
val date = Date(stamp.time)

val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")

// set your timezone appropriately or use `TimeZone.getDefault()`
sdf.timeZone = TimeZone.getTimeZone("Asia/Kolkata") 

val formattedDate = sdf.format(date)

println(formattedDate)

Kotlin Playground link

Improvements

  • Set time zone to get correct time otherwise you will get the UTC time.
  • Formatted the date time according to yyyy-MM-dd HH:mm:ss format.
  • Disambiguate the Timestamp class import by commenting the required import.
  • Added Kotlin Playground link to see a working example.
  fun stringtoDate(dates: String): Date {
        val sdf = SimpleDateFormat("EEE, MMM dd yyyy",
                Locale.ENGLISH)
        var date: Date? = null
        try {
             date = sdf.parse(dates)
            println(date)
        } catch (e: ParseException) {
            e.printStackTrace()
        }
        return date!!
    }

If you're trying to convert timestamp from firebase. This is what worked for me.

val timestamp = data[TIMESTAMP] as com.google.firebase.Timestamp
val date = timestamp.toDate()

This works for me.

 fun FromTimestamp(value: Long?): Date? {
        return if (value == null) null else Date(value)
    }
private fun epochToIso8601(time: Long): String {
    val format = "dd MMM yyyy HH:mm:ss" // you can add the format you need
    val sdf = SimpleDateFormat(format, Locale.getDefault()) // default local
    sdf.timeZone = TimeZone.getDefault() // set anytime zone you need
    return sdf.format(Date(time * 1000))
}

The above code will get the time in long format, which is the default epoch format and return it as a string to display.

In case you have input as a string just add .toLong() and it will be converted to long.

Related