64

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.

this link is not an answer to my question

8
  • You should provide the Java code you would use that is "very simple" to make it easier for someone to show you the Kotlin equivalent. Commented Nov 12, 2017 at 15:15
  • Do you mean this? programiz.com/kotlin-programming/examples/current-date-time Commented Nov 12, 2017 at 15:24
  • @Luzo convert for example convert 1510500494 as timestamp to for example: 2017-01-01 Commented Nov 12, 2017 at 15:29
  • 2
    That's not what I'm suggesting. I'm just suggesting you ask IntelliJ to convert the Java code to Kotlin. But if you're not familiar with Kotlin, why don't you become familiar with it before using Kotlin? And you still haven't posted the very simple Java code. Commented Nov 12, 2017 at 16:00
  • 2
    That is irrelevant. You still haven't posted the very simple Java code. Commented Nov 12, 2017 at 16:08

14 Answers 14

50
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()
    }
}
Sign up to request clarification or add additional context in comments.

7 Comments

val netDate = Date(s.toLong() * 1000) worked for me.
Is this to current locale?
@temp_ your suggestion is correct because the TimeStamp is in Seconds and Date constructor accept in parameter date on milliseconds
* @param date the milliseconds since January 1, 1970, 00:00:00 GMT.
Why multiply by *1000?
|
18

It's actually just like Java. Try this:

val stamp = Timestamp(System.currentTimeMillis())
val date = Date(stamp.time)
println(date)

1 Comment

Error with Date..
15
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.

2 Comments

I was stuck for ages - the 1000L bit saved me. Thank you
@HaiderMalik, thank you! I also got different bugs when multiplied by 1000 and when forgot to divide Java date by 1000L when sent requests to a server.
14

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

3 Comments

require API level 26+
I suppose you mean Android API 26? I do not know about that, what I suggested is pure Kotlin & Java.
Yes, in android, this api requires API 26.
10

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

1 Comment

This is the answer I was looking for. Thanks a lot for the answer.
8
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).

1 Comment

I doubt that this helps, or even works at all. To convince me otherwise please explain how this works and why it solves the problem.
6

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

Comments

5
@SuppressLint("SimpleDateFormat")
fun dateFormatter(milliseconds: String): String {
    return SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(Date(milliseconds.toLong())).toString()
}

Comments

4

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.

1 Comment

The third line here should be val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
2

I did something like this with extension function:

import java.time.Instant.ofEpochSecond
import java.time.LocalDateTime
import java.time.ZoneOffset.UTC

fun main() {
  val localDateTime = 1510500494L.toLocalDateTime()
}

private fun Long.toLocalDateTime() = ofEpochSecond(this).atZone(UTC).toLocalDateTime()

Comments

1
  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!!
    }

Comments

1

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

Comments

1
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.

Comments

0

This works for me.

 fun FromTimestamp(value: Long?): Date? {
        return if (value == null) null else Date(value)
    }

1 Comment

It was easier to set value?.let { Date(it) }.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.