How can I get the current time from device? I need possibly ways in kotlin language.
Asked
Active
Viewed 4,584 times
3 Answers
5
Here simple way to get the time!
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)

Partha
- 453
- 4
- 11
4
try this...
LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
ex) 2021-12-02 17:17:03
LocalDateTime.now() require API level 26.
so, if API level 26 below,
you add @RequiresApi(Build.VERSION_CODES.0)
this code above your method.

a_local_nobody
- 7,947
- 5
- 29
- 51

bdeviOS
- 449
- 1
- 6
0
Don't use old Calendar apis, it's outdated and troublesome.
Use LocalDateTime
to get the system date and time
private fun getCurrentDate() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val dateTime = LocalDateTime.now() // date time object
val month = dateTime.month // result DECEMBER
val date = dateTime.dayOfMonth // result 2 (current date )
val formatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM)
Log.d(
"Date:", parssed date ${dateTime.format(formatter)}"
)
}
}
Change FormatStyle
to MEDIUM
,SHORT
,LONG
,FULL
to change date format accordingly or you can use custom date parser format.
Output: Dec 2, 2021
Note: DateTimeFormatter
only works in android 8 and above, to use it below android 8 enable desugaring

Nitish
- 3,075
- 3
- 13
- 28