2

I want to get the first day of the week but I have a strange bug. If I use this code:

Calendar cal = Calendar.getInstance();
cal.set(2017, 0, 1);

cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek());
DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.FULL, Locale.getDefault());
Log.d(TAG, "Date: " + dateFormat.format(cal.getTime()));

My log displays the wrong date: D/Activity: Date: lundi 2 janvier 2017

But if I use the getTime() method just like this:

Calendar cal = Calendar.getInstance();
cal.set(2017, 0, 1);
cal.getTime(); // Here

cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek());
DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.FULL, Locale.getDefault());
Log.d(TAG, "Date: " + dateFormat.format(cal.getTime()));

My log display the correct date: D/Activity: Date: lundi 26 décembre 2016

My phone uses the French language so my week begins on Monday.

Somebody knows why?

Floern
  • 33,559
  • 24
  • 104
  • 119
Louis
  • 406
  • 6
  • 13
  • Note that the legacy date-time API (`java.util` date-time types and their formatting type, `SimpleDateFormat` etc.) is outdated and error-prone. It is recommended to stop using it completely and switch to `java.time`, the [modern date-time API](https://www.oracle.com/technical-resources/articles/java/jf14-date-time.html). Check [this answer](https://stackoverflow.com/a/67577875/10819573) based on the modern date-time API. – Arvind Kumar Avinash May 18 '21 at 08:30

1 Answers1

3

Java's Calendar API is infamous for its behavior regarding updating fields. The problem is that multiple set() calls may lead to some unexpected result because some internals don't get adjusted properly, i.e. it doesn't update some values until it really has to, e.g. when you call getTime().

You can read more on this post.

So, the fix for this issue is indeed to call getTime() or getTimeInMillis() in between.

Community
  • 1
  • 1
Floern
  • 33,559
  • 24
  • 104
  • 119