[android] How to get current local date and time in Kotlin

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?

This question is related to android datetime kotlin

The answer is


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

Try this:

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

You can use your own pattern as well, e.g.

val sdf = SimpleDateFormat("yyyy.MM.dd")
// 2020.02.02

To get local formatting use getDateInstance(), getDateTimeInstance(), or getTimeInstance(), or use new SimpleDateFormat(String template, Locale locale) with for example Locale.US for ASCII dates. The first three options require API level 29.


To get the current Date in Kotlin do this:

val dateNow = Calendar.getInstance().time

I use this to fetch data from API every 20 seconds

 private fun isFetchNeeded(savedAt: Long): Boolean {
        return savedAt + 20000 < System.currentTimeMillis()
    }

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

Try this :

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

Another solution is changing the api level of your project in build.gradle and this will work.


You can get current year, month, day etc from a calendar instance

val c = Calendar.getInstance()

val year = c.get(Calendar.YEAR)
val month = c.get(Calendar.MONTH)
val day = c.get(Calendar.DAY_OF_MONTH)

val hour = c.get(Calendar.HOUR_OF_DAY)
val minute = c.get(Calendar.MINUTE)

If you need it as a LocalDateTime, simply create it by using the parameters you got above

val myLdt = LocalDateTime.of(year, month, day, ... )

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to datetime

Comparing two joda DateTime instances How to format DateTime in Flutter , How to get current time in flutter? How do I convert 2018-04-10T04:00:00.000Z string to DateTime? How to get current local date and time in Kotlin Converting unix time into date-time via excel Convert python datetime to timestamp in milliseconds SQL Server date format yyyymmdd Laravel Carbon subtract days from current date Check if date is a valid one Why is ZoneOffset.UTC != ZoneId.of("UTC")?

Examples related to kotlin

No Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator How to allow all Network connection types HTTP and HTTPS in Android (9) Pie? Deprecated Gradle features were used in this build, making it incompatible with Gradle 5.0 Default interface methods are only supported starting with Android N Error : Program type already present: android.support.design.widget.CoordinatorLayout$Behavior Cannot inline bytecode built with JVM target 1.8 into bytecode that is being built with JVM target 1.6 startForeground fail after upgrade to Android 8.1 How to get current local date and time in Kotlin How to add an item to an ArrayList in Kotlin? HTTP Request in Kotlin