I am trying to get the current day of the year as an integer to access within my program. I looked at the Kotlin Docs and found a function called getDay(). but when I type it into my program it gives me an error and says the function is not determined. I am using Android Studio with Kotlin and the minimum API is 21.
CodePudding user response:
Date().getDay()
or rather Date().day
in Kotlin returns the day of the week so not what you want.
Calendar.getInstance().get(Calendar.DAY_OF_YEAR)
is the correct function to use in Android.
Calendar
, Date
etc. have been replaced by new java.util.time
classes with Java 8 so you should use LocalDate.now().dayOfYear
but as @nuhkoca indicates in order to do that you need to enable Java 8 API desugaring support which is basically adding this to your build file (Kotlin DSL not Groovy):
compileOptions {
isCoreLibraryDesugaringEnabled = true
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = "1.8"
}
CodePudding user response:
This getDay() method is part of the Date class. Check this: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.js/-date/get-day.html
You must do something like:
val currentDay = Date().getDay()
CodePudding user response:
try this code :
import java.time.LocalDate
import java.util.*
fun main() {
val cal = Calendar.getInstance()
val day = cal[Calendar.DATE]
val doy = cal[Calendar.DAY_OF_YEAR]
println("Current Date: " cal.time)
println("Day : $day")
println("Day of Year : $doy")
}
CodePudding user response:
If you perform desugaring in order to be able to use Java 8 Time API
back to API 21, you can then use this method to get the day of year
import java.time.LocalDate
val dayOfYear = LocalDate.now().dayOfYear
System.out.println(dayOfYear);
Answer: 289