151

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?

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
rgoncalv
  • 5,825
  • 6
  • 34
  • 61
  • 5
    For API levels lower than 26 just add [the ThreeTenABP library](https://github.com/JakeWharton/ThreeTenABP) to your project, import `org.threeten.bp.LocalDateTime` and then do as you tried: `LocalDateTime.now(yourTimeZone)` (I recommend specifying time zone, but if you don’t you’ll get the JVM time zone setting). See more in [this question: How to use ThreeTenABP in Android Project](https://stackoverflow.com/questions/38922754/how-to-use-threetenabp-in-android-project). – Ole V.V. Jul 18 '18 at 09:59
  • check this link for your needed solution : https://stackoverflow.com/questions/3747490/android-get-date-before-7-days-one-week/57674721#57674721 – Prashant Jajal Aug 27 '19 at 12:29

14 Answers14

104

Try this :

 val sdf = SimpleDateFormat("dd/M/yyyy hh:mm:ss")
 val currentDate = sdf.format(Date())
 System.out.println(" C DATE is  "+currentDate)
Soleil
  • 6,404
  • 5
  • 41
  • 61
Shan Mk
  • 1,219
  • 1
  • 9
  • 7
60

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")
Linh
  • 57,942
  • 23
  • 262
  • 279
  • 5
    this should be the accpted answer: easy and clean, I implemented it as a package level function (on package level functions: https://stackoverflow.com/questions/38778882/how-to-create-package-level-functions) to reach it from anywhere – oneManArmin Oct 17 '19 at 18:37
54

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.

ephemient
  • 198,619
  • 38
  • 280
  • 391
21

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, ... )
J7bits
  • 688
  • 8
  • 14
11

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.

Marci
  • 899
  • 10
  • 13
Nawaraj Bista
  • 326
  • 4
  • 12
7

To get the current Date in Kotlin do this:

val dateNow = Calendar.getInstance().time
Thiago
  • 12,778
  • 14
  • 93
  • 110
7
fun main(){
println(LocalDateTime.now().toString()) //2021-10-25T12:03:04.524
println(Calendar.getInstance().time) //Mon Oct 25 12:02:23 GST 2021
}

There are the above options, with the output added as comment.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Akash Verma
  • 638
  • 1
  • 11
  • 15
6

You can use this function

fun getCurrentDate():String{
val sdf = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS")
return sdf.format(Date())
}
pavel
  • 1,603
  • 22
  • 19
2
fun now(): String {
    return SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(Date())
}


    val currentYear = SimpleDateFormat("yyyy",Locale.getDefault()).format(Date())
    val currentMonth = SimpleDateFormat("MM",Locale.getDefault()).format(Date())
    val currentDay = SimpleDateFormat("dd",Locale.getDefault()).format(Date())
  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 27 '21 at 20:52
1

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

Assuming that we got time in seconds we can do something like: (koltin language)

val dateObject = Date(timeInMillis)
val calendarInstance = Calendar.getInstance()
calendarInstance.time = dateObject
val hour = calendarInstance.get(Calendar.HOUR)
val minute = calendarInstance.get(Calendar.MINUTE)
val ampm = if(calendarInstance.get(Calendar.AM_PM)==0) "AM " else "PM "
val date = calendarInstance.get(Calendar.DATE)
val month = calendarInstance.get(Calendar.MONTH)
val year = calendarInstance.get(Calendar.YEAR)
Mr. Techie
  • 622
  • 7
  • 17
0

Use this simple and easy

private fun getTime(): String =
        SimpleDateFormat("hh:mm:ss a", Locale.getDefault()).format(Date())

set any desire format of date

toyota Supra
  • 3,181
  • 4
  • 15
  • 19
-5

I use this to fetch data from API every 20 seconds

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

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

Sebastian
  • 27
  • 11