如何将Long值转换为日期时间并将当前时间转换为Long kotlin?

Hel*_*oCW 5 android kotlin

代码A可以将long值转换为日期值,就像2018.01.10

  1. 我希望获得日期+时间值,例如2018.01.10 23:11,我该如何使用Kotlin?

  2. 我希望将当前时间转换为长值,如何使用Kotlin?

谢谢!

代码A

fun Long.toDateString(dateFormat: Int =  DateFormat.MEDIUM): String {
    val df = DateFormat.getDateInstance(dateFormat, Locale.getDefault())
    return df.format(this)
}
Run Code Online (Sandbox Code Playgroud)

Meo*_*der 11

试试这个,我使用SimpleDataFormat。

fun convertLongToTime(time: Long): String {
    val date = Date(time)
    val format = SimpleDateFormat("yyyy.MM.dd HH:mm")
    return format.format(date)
}

fun currentTimeToLong(): Long {
    return System.currentTimeMillis()
}

fun convertDateToLong(date: String): Long {
    val df = SimpleDateFormat("yyyy.MM.dd HH:mm")
    return df.parse(date).time
}
Run Code Online (Sandbox Code Playgroud)

并使用Android Studio将Java文件转换为kotlin文件,选择 Code->Convert java file to kotlin file.


Dav*_*vid 8

不需要任何复杂的东西:

获取当前时间和日期作为Date对象

val dateTime: Date = Calendar.getInstance().time
Run Code Online (Sandbox Code Playgroud)

将其转换为Long

val dateTimeAsLong: Long = dateTime.time
Run Code Online (Sandbox Code Playgroud)

将其转换LongDate

val backToDate: Date = Date(dateTimeAsLong)
Run Code Online (Sandbox Code Playgroud)