11

My friends and I are developing an app in android studio using Kotlin. We are quite new in app development but we have decent prior programming skills. For one of our functionalities we need to get current date and time. We tried all kinds of imports and methods, but none seem to work with SDK lower than 26. With our app we target devices with minimum API 19. For example:

package hr.com.wap.wap

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_tomorrow_view.*
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter

class TomorrowView : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_tomorrow_view)

        val current = LocalDateTime.now()

        val formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy. HH:mm:ss")

        label_date.text = current.format(formatter)
    }
}

The error we get is: Call requires API level 26 (current min is 19). We know that we can test our app using a virtual device with minSdk 26, but since target a wider range of devices (minSdk 19) we are wondering is there some way to bypass that error? Thanks in advance!

hollowkiki
  • 113
  • 1
  • 1
  • 4

3 Answers3

29

Use this, handle versions lower than android Oreo(O), using a SimpleDateFormater

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        val current = LocalDateTime.now()
        val formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy. HH:mm:ss")
        var answer: String =  current.format(formatter)
        Log.d("answer",answer)
    } else {
        var date = Date()
        val formatter = SimpleDateFormat("MMM dd yyyy HH:mma")
        val answer: String = formatter.format(date)
        Log.d("answer",answer)
    }
Jai Govindani
  • 3,181
  • 21
  • 26
Dracarys
  • 714
  • 7
  • 16
7

For Date

val currentDate: String = SimpleDateFormat("dd/MM/yyyy", Locale.getDefault()).format(Date())

For Time

val currentTime: String = SimpleDateFormat("HH:mm:ss", Locale.getDefault()).format(Date())
Aftab Alam
  • 1,969
  • 17
  • 17
4

Check this useful thread with similar question.

In a nutshell, you can use adaptation of the JSR-310(new Data/Time API) for Android.

https://github.com/JakeWharton/ThreeTenABP

Then you can use LocalDateTime in the application.

Maxim
  • 1,194
  • 11
  • 24
  • Also [How to use ThreeTenABP in Android Project](https://stackoverflow.com/questions/38922754/how-to-use-threetenabp-in-android-project). – Ole V.V. Jun 23 '18 at 22:24