HelloCW
HelloCW

Reputation: 2325

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

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

Upvotes: 35

Views: 61787

Answers (5)

Sohaib Ahmed
Sohaib Ahmed

Reputation: 3098

private val simpleDateFormat by lazy { SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()) }

fun getDate(timeStamp: Long): String {
    return simpleDateFormat.format(Date(timeStamp))
}

Upvotes: 0

Mahmoud Elebiary
Mahmoud Elebiary

Reputation: 123

Convert long to Date String with the format:

fun Long.convertMilliSecondsToDate(): String {
            val date = Date(this)
            val format = SimpleDateFormat("yyyy.MM.dd HH:mm", Locale.ENGLISH)
            return format.format(date)
        }

Upvotes: 0

RealityExpander
RealityExpander

Reputation: 344

I like to use extension functions, as so...

Convert long to Time & Date String:

fun Long.toTimeDateString(): String {
    val dateTime = java.util.Date(this)
    val format = SimpleDateFormat("HH:mm:ss dd/MM/yyyy", Locale.US)
    return format.format(dateTime)
}

Convert Time & Date String to Long:

fun String.toTimeDateLong(): Long {
    val format = SimpleDateFormat("HH:mm:ss dd/MM/yyyy", Locale.US)
    return format.parse(this)?.time ?: throw IllegalArgumentException("Invalid time string")
}

To use:

fun main() {
   val timeDateLong = "10:23:12 12/11/2022".toTimeDateLong()
   
   val timeDateStr = timeDateLong.toTimeDateString()
}

Upvotes: 3

David
David

Reputation: 1017

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)

Upvotes: 8

Tung Tran
Tung Tran

Reputation: 2955

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.

Upvotes: 77

Related Questions