How to get current local date and time in Kotlin

前端 未结 9 1954
半阙折子戏
半阙折子戏 2021-01-31 13:24

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

9条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-31 13:53

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

提交回复
热议问题