What you want to achieve is much easier using Java 8's date / time library (java.time
) instead of Calendar
.
import java.time.DayOfWeek
import java.time.LocalDate
import java.time.format.DateTimeFormatter
import java.time.temporal.TemporalAdjusters
fun getWeekDay(): Array<String?> {
var date = LocalDate.of(2021, 1, 29)
date = date.with(TemporalAdjusters.previousOrSame(DayOfWeek.SUNDAY))
val formatter = DateTimeFormatter.ofPattern("dd (EEE)")
val days = arrayOfNulls<String>(7)
for (i in 0 until 7) {
days[i] = formatter.format(date)
date = date.plusDays(1)
}
return days
}
The code starts from a given date (I have hard-coded it here but you can adjust it), goes back to the previous or same Sunday and simply adds seven days.
To be able to use it in all android versions, add this dependency to your build.gradle
file:
coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:1.1.1'
and these compile options:
android {
...
compileOptions {
coreLibraryDesugaringEnabled true
targetCompatibility JavaVersion.VERSION_1_8
sourceCompatibility JavaVersion.VERSION_1_8
}
...
Now you will be able to use a lot of Java 8 features and libraries.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…