How to get current local date and time in Kotlin

2020-02-10 00:16发布

问题:

How to get current Date (day month and year) and time (hour, minutes and seconds) all in local time in Kotlin?

I tried through LocalDateTime.now() but it is giving me an error saying Call requires API Level 26 (curr min is 21).

How could I get time and date in Kotlin?

回答1:

java.util.Calendar.getInstance() represents the current time using the current locale and timezone.

You could also choose to import and use Joda-Time or one of the forks for Android.



回答2:

Try this :

 val sdf = SimpleDateFormat("dd/M/yyyy hh:mm:ss")
 val currentDate = sdf.format(Date())
 System.out.println(" C DATE is  "+currentDate)


回答3:

My utils method for get current date time using Calendar when our minSdkVersion < 26.

fun Date.toString(format: String, locale: Locale = Locale.getDefault()): String {
    val formatter = SimpleDateFormat(format, locale)
    return formatter.format(this)
}

fun getCurrentDateTime(): Date {
    return Calendar.getInstance().time
}

Using

import ...getCurrentDateTime
import ...toString
...
...
val date = getCurrentDateTime()
val dateInString = date.toString("yyyy/MM/dd HH:mm:ss")


回答4:

Try this:

val date = Calendar.getInstance().time
val formatter = SimpleDateFormat.getDateTimeInstance() //or use getDateInstance()
val formatedDate = formatter.format(date)


回答5:

checkout these easy to use Kotlin extensions for date format

fun String.getStringDate(initialFormat: String, requiredFormat: String, locale: Locale = Locale.getDefault()): String {
    return this.toDate(initialFormat, locale).toString(requiredFormat, locale)
}

fun String.toDate(format: String, locale: Locale = Locale.getDefault()): Date = SimpleDateFormat(format, locale).parse(this)

fun Date.toString(format: String, locale: Locale = Locale.getDefault()): String {
    val formatter = SimpleDateFormat(format, locale)
    return formatter.format(this)
}