60

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

starball
  • 20,030
  • 7
  • 43
  • 238
DolDurma
  • 15,753
  • 51
  • 198
  • 377
  • 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. – dominicoder Nov 12 '17 at 15:15
  • Do you mean this? https://www.programiz.com/kotlin-programming/examples/current-date-time – Luzo Nov 12 '17 at 15:24
  • @Luzo convert for example convert `1510500494` as timestamp to for example: `2017-01-01` – DolDurma Nov 12 '17 at 15:29
  • Write the very simple Java code, ask IntelliJ to convert it to Java for you? That said, it's a simple method call, so why would it be different in Kotlin? – JB Nizet Nov 12 '17 at 15:45
  • @JBNizet i'm not familiar of kotlin, then i dont khow how can i use java in kotlin – DolDurma Nov 12 '17 at 15:58
  • 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. – JB Nizet Nov 12 '17 at 16:00
  • @JBNizet i'm customizing client of `Rocket.Chat` for android – DolDurma Nov 12 '17 at 16:04
  • 2
    That is irrelevant. You still haven't posted the very simple Java code. – JB Nizet Nov 12 '17 at 16:08

13 Answers13

47
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()
    }
}
Sofien Rahmouni
  • 4,354
  • 1
  • 21
  • 22
arjun shrestha
  • 1,379
  • 1
  • 10
  • 13
15

It's actually just like Java. Try this:

val stamp = Timestamp(System.currentTimeMillis())
val date = Date(stamp.time)
println(date)
user158
  • 12,852
  • 7
  • 62
  • 94
Javier García Manzano
  • 1,024
  • 2
  • 12
  • 25
14
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.

CoolMind
  • 26,736
  • 15
  • 188
  • 224
13

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()
t0r0X
  • 4,212
  • 1
  • 38
  • 34
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()
}
Anga
  • 2,450
  • 2
  • 24
  • 30
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).

Sahil Gaikwad
  • 99
  • 1
  • 2
  • 3
    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. – Yunnosch Mar 17 '20 at 06:17
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()
        }
   }
John Fraize
  • 61
  • 1
  • 2
4
@SuppressLint("SimpleDateFormat")
fun dateFormatter(milliseconds: String): String {
    return SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(Date(milliseconds.toLong())).toString()
}
wadali
  • 2,221
  • 1
  • 20
  • 38
3

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.
Abhishek Bedi
  • 5,205
  • 2
  • 36
  • 62
user158
  • 12,852
  • 7
  • 62
  • 94
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!!
    }
Umesh Maharjan
  • 312
  • 2
  • 6
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()
Mr. Disability
  • 799
  • 1
  • 10
  • 19
0

This works for me.

 fun FromTimestamp(value: Long?): Date? {
        return if (value == null) null else Date(value)
    }
0
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.

Syed Afeef
  • 140
  • 1
  • 9