'How can I convert a Long value to date time and convert current time to Long kotlin?
The Code A can convert a long value to date value, just like 2018.01.10
I hope to get Date + Time value , such as 2018.01.10 23:11, how can I do with Kotlin?
I hope to convert current time to a long value , how can I do with Kotlin?
Thanks!
Code A
fun Long.toDateString(dateFormat: Int = DateFormat.MEDIUM): String {
val df = DateFormat.getDateInstance(dateFormat, Locale.getDefault())
return df.format(this)
}
Solution 1:[1]
Try this, I use 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
}
And to convert java file to kotlin file with Android Studio, choosing Code->Convert java file to kotlin file.
Solution 2:[2]
No need for anything complex:
Get current time and date as a Date
object
val dateTime: Date = Calendar.getInstance().time
Convert it to a Long
val dateTimeAsLong: Long = dateTime.time
Convert that Long
back to a Date
val backToDate: Date = Date(dateTimeAsLong)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 |