Louis
Louis

Reputation: 416

Android Calendar getFirstDayOfWeek bug

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?

Upvotes: 2

Views: 344

Answers (1)

Floern
Floern

Reputation: 33904

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.

Upvotes: 3

Related Questions