Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert a Long value to date time and convert current time to Long kotlin?

Tags:

The Code A can convert a long value to date value, just like 2018.01.10

  1. I hope to get Date + Time value , such as 2018.01.10 23:11, how can I do with Kotlin?

  2. 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) } 
like image 276
HelloCW Avatar asked Mar 29 '18 08:03

HelloCW


People also ask

How do you change the time on Kotlin?

As Kotlin is interoperable with Java, we will be using Java utility class and Simple Date Format class in order to convert TimeStamp into DateTime.

How do I get the current date and time in Kotlin?

As Kotlin is interoperable with Java, we will be using the Java utility class and Simple Date Format class in order to get the current local date and time.


2 Answers

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.

like image 63
Tung Tran Avatar answered Oct 14 '22 21:10

Tung Tran


No need for anything complex:

Get current time and date as a Date object

val dateTime = Calendar.getInstance().time // Date 

Convert it to a Long

val dateTimeAsLong = dateTime.time // Long 

Convert that Long back to a Date

val backToDate = Date(dateTimeAsLong) // Date 
like image 25
David Avatar answered Oct 14 '22 23:10

David