How to get current local date and time in Kotlin

前端 未结 9 1932
半阙折子戏
半阙折子戏 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, ... )
    
    0 讨论(0)
  • 2021-01-31 13:38

    To get the current Date in Kotlin do this:

    val dateNow = Calendar.getInstance().time
    
    0 讨论(0)
  • 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)
    }
    
    0 讨论(0)
  • 2021-01-31 13:41

    Another solution is changing the api level of your project in build.gradle and this will work.

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

    Try this :

     val sdf = SimpleDateFormat("dd/M/yyyy hh:mm:ss")
     val currentDate = sdf.format(Date())
     System.out.println(" C DATE is  "+currentDate)
    
    0 讨论(0)
  • 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")
    
    0 讨论(0)
提交回复
热议问题