Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date and time in Android studio (Kotlin language)

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!

like image 376
hollowkiki Avatar asked Jun 23 '18 07:06

hollowkiki


2 Answers

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)
    }
like image 85
Dracarys Avatar answered Oct 16 '22 15:10

Dracarys


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())
like image 44
Aftab Alam Avatar answered Oct 16 '22 16:10

Aftab Alam