Kotlin convert TimeStamp to DateTime

2019-06-27 22:39发布

问题:

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 1070-01-01) 1510500494 ==> DateTime object 2017-11-12 03: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

回答1:

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


回答2:

It's actually just like Java. Try this:

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


回答3:

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


回答4:

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


回答5:

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