How to get current local date and time in Kotlin

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

    java.util.Calendar.getInstance() represents the current time using the current locale and timezone.

    You could also choose to import and use Joda-Time or one of the forks for Android.

    0 讨论(0)
  • 2021-01-31 13:58

    I use this to fetch data from API every 20 seconds

     private fun isFetchNeeded(savedAt: Long): Boolean {
            return savedAt + 20000 < System.currentTimeMillis()
        }
    
    0 讨论(0)
  • 2021-01-31 13:59

    Try this:

    val date = Calendar.getInstance().time
    val formatter = SimpleDateFormat.getDateTimeInstance() //or use getDateInstance()
    val formatedDate = formatter.format(date)
    

    You can use your own pattern as well, e.g.

    val sdf = SimpleDateFormat("yyyy.MM.dd")
    // 2020.02.02
    

    To get local formatting use getDateInstance(), getDateTimeInstance(), or getTimeInstance(), or use new SimpleDateFormat(String template, Locale locale) with for example Locale.US for ASCII dates. The first three options require API level 29.

    0 讨论(0)
提交回复
热议问题