Date and time in Android studio (Kotlin language)

|▌冷眼眸甩不掉的悲伤 提交于 2020-06-12 03:30:10

问题


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!


回答1:


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



回答2:


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.




回答3:


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


来源:https://stackoverflow.com/questions/50999112/date-and-time-in-android-studio-kotlin-language

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!