If I understand correctly, you want to consider Sunday the first day of the week (as in USA).
WeekFields wf = WeekFields.SUNDAY_START;
LocalDate today = LocalDate.now(ZoneId.of("Europe/Warsaw"));
LocalDate firstDayOfThisWeek = today.with(wf.dayOfWeek(), 1);
System.out.println(firstDayOfThisWeek);
I am writing Java code and trusting you to transform to Kotlin. Running today (Tuesday, May 29) this printed
2018-05-27
If instead you want Monday as first day of the week (as in Poland and as the international standard says), just use WeekFields.ISO
instead of WeekFields.SUNDAY_START
. If you want it to depend on locale, use for example WeekFields.of(Locale.forLanguageTag("pl-PL"))
.
Another and possibly clearer option is:
LocalDate firstDayOfThisWeek = today
.with(TemporalAdjusters.previousOrSame(DayOfWeek.SUNDAY));
In both cases I use java.time
, the modern Java date and time API. I think that this is a nice example of where it provides for clearer code, which is often the case compared to the old date and time classes like Calendar
.
What went wrong in your code?
As I understand the documentation, your code should give the Sunday of the current week. Calendar
uses 1 for Sunday. You might have used calendar.set(DAY_OF_WEEK, SUNDAY)
to obtain exactly the same. When I run it today, I get 27 May when using Sunday as first day of week and 3 June when using Monday as first day (which means Sunday is the last day of the week). The documentation is not very clear, though, and the Calendar
class can be confusing. In any case, probably this was also what happened when you tried on different devices: they had different definitions of weeks. This may be possible even if they have the same locale if you can configure week definitions separately.
Question: Can I use java.time on Android?
Yes, java.time
works nicely on older and newer Android devices. It just requires at least Java 6.
- In Java 8 and later and on newer Android devices (from API level 26, I’m told) the modern API comes built-in.
- In Java 6 and 7 get the ThreeTen Backport, the backport of the new classes (ThreeTen for JSR 310; see the links at the bottom).
- On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from
org.threeten.bp
with subpackages.
Links