Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
349 views
in Technique[技术] by (71.8m points)

date - Start week with SUNDAY format using Kotlin in android

I am working on Calendar dates, where I am making 7 Days week value from below method. But I need to start my week days from SUNDAY specific only.

fun getWeekDay(): Array<String?>? {
        weekDaysCount--
        val now1 = Calendar.getInstance()
        now1.set(2021, 1, 29)
        val now = now1.clone() as Calendar

        val format = SimpleDateFormat("yyyy-MM-dd")
        val days = arrayOfNulls<String>(7)
        val delta = -now[GregorianCalendar.DAY_OF_WEEK] + 1
        now.add(Calendar.WEEK_OF_YEAR, weekDaysCount)
        now.add(Calendar.DAY_OF_MONTH, delta)
        for (i in 0..6) {
            days[i] = format.format(now.time)
            now.add(Calendar.DAY_OF_MONTH, 1)
        }

        return days
    }

I am getting an output like this:

enter image description here

I need to make a method where if i give any Date, it should adjust as per SUNDAY format.

As per Date 29/1/2021, output should be like:

24(Sun), 25 (Mon), 26 (Tue), 27 (Wed), 28 (Thur) 29 (Fri), 30 (Sat)
question from:https://stackoverflow.com/questions/65540656/start-week-with-sunday-format-using-kotlin-in-android

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...