How to get current local date and time in Kotlin

前端 未结 9 2175
半阙折子戏
半阙折子戏 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:40

    checkout these easy to use Kotlin extensions for date format

    fun String.getStringDate(initialFormat: String, requiredFormat: String, locale: Locale = Locale.getDefault()): String {
        return this.toDate(initialFormat, locale).toString(requiredFormat, locale)
    }
    
    fun String.toDate(format: String, locale: Locale = Locale.getDefault()): Date = SimpleDateFormat(format, locale).parse(this)
    
    fun Date.toString(format: String, locale: Locale = Locale.getDefault()): String {
        val formatter = SimpleDateFormat(format, locale)
        return formatter.format(this)
    }
    

提交回复
热议问题