How to get current local date and time in Kotlin

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

    You can get current year, month, day etc from a calendar instance

    val c = Calendar.getInstance()
    
    val year = c.get(Calendar.YEAR)
    val month = c.get(Calendar.MONTH)
    val day = c.get(Calendar.DAY_OF_MONTH)
    
    val hour = c.get(Calendar.HOUR_OF_DAY)
    val minute = c.get(Calendar.MINUTE)
    

    If you need it as a LocalDateTime, simply create it by using the parameters you got above

    val myLdt = LocalDateTime.of(year, month, day, ... )
    

提交回复
热议问题