Kotlin将TimeStamp转换为DateTime

Dol*_*rma 10 java timestamp kotlin

我试图找出如何我可以转换timestampdatetime在科特林,这是Java很简单,但我不能找到在科特林它的任何等同.

例如:纪元时间戳(自1070-01-01以来的秒数)1510500494==> DateTime对象2017-11-12 03:28:14.

在Kotlin中是否有任何解决方案,或者我必须在Kotlin中使用Java语法?请给我一个简单的示例,以说明如何解决此问题.提前致谢.

这个链接不是我的问题的答案

arj*_*tha 12

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()
    }
}
Run Code Online (Sandbox Code Playgroud)

  • val netDate = Date(s.toLong()* 1000)为我工作。 (3认同)

Ang*_*oko 10

这是 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()
}
Run Code Online (Sandbox Code Playgroud)


t0r*_*r0X 9

虽然是 Kotlin,但还是得使用 Java API。转换1510500494您在问题评论中提到的值的 Java 8+ API 示例:

import java.time.*

val dt = Instant.ofEpochSecond(1510500494)
                .atZone(ZoneId.systemDefault())
                .toLocalDateTime()
Run Code Online (Sandbox Code Playgroud)

  • 我想你的意思是“Android API 26”?我不知道这一点,我建议的是纯 Kotlin & Java。 (4认同)

Sah*_*wad 6

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)
Run Code Online (Sandbox Code Playgroud)

“sdf”是变量“SimpleDateFormat”,我们可以根据需要设置日期格式。

“netDate”是日期的变量。在 Date 中,我们可以使用 sdf.format(netDate) 发送时间戳值并通过 SimpleDateFormat 打印该日期。

  • 我怀疑这是否有帮助,甚至根本不起作用。为了说服我,请解释它是如何工作的以及为什么它可以解决问题。 (2认同)

Coo*_*ind 6

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)

}
Run Code Online (Sandbox Code Playgroud)

请注意,我们乘以1000L,而不是 1000。如果您将整数 (1560507488) 乘以 1000,您将得到错误的结果:1970 年 1 月 17 日,17 : 25 : 59


Jav*_*ano 5

实际上就像Java。尝试这个:

val stamp = Timestamp(System.currentTimeMillis())
val date = Date(stamp.getTime())
println(date)
Run Code Online (Sandbox Code Playgroud)


小智 5

这对我有用 - 需要很长时间

    import java.time.*

    private fun getDateTimeFromEpocLongOfSeconds(epoc: Long): String? {
        try {
            val netDate = Date(epoc*1000)
            return netDate.toString()
        } catch (e: Exception) {
            return e.toString()
        }
   }
Run Code Online (Sandbox Code Playgroud)