user2955733
user2955733

Reputation: 385

The following code in Java and Android results to differ

The following code produces different results when I run it in Java as opposed to when I run it on Android:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

Calendar cal = Calendar.getInstance();//

for(int k = 1; k < 10; k++) {
    cal.set(Calendar.YEAR, 2013);
    cal.set(Calendar.WEEK_OF_YEAR, k);
    cal.set(Calendar.DAY_OF_WEEK, 1);
    System.out.println(sdf.format(cal.getTime()));
} 


The result on Java (JDK 1.6):

java


The result on Android (Emulator with Android 4.2.2): enter image description here

Why is this the case? How can I fix this?

Upvotes: 1

Views: 105

Answers (1)

Elemental
Elemental

Reputation: 7476

Following the rules in the Android developers documentation here it seems it should work by virtue of the last rule (and the fact that these have been set most recently).

Inconsistent information. If fields conflict, the calendar will give preference to fields set more recently. For example, when determining the day, the calendar will look for one of the following combinations of fields. The most recent combination, as determined by the most recently set single field, will be used.

 MONTH + DAY_OF_MONTH
 MONTH + WEEK_OF_MONTH + DAY_OF_WEEK
 MONTH + DAY_OF_WEEK_IN_MONTH + DAY_OF_WEEK
 DAY_OF_YEAR
 DAY_OF_WEEK + WEEK_OF_YEAR

A possible bug in the Android implementation? I would try setting the DAY Of Week first and then the month that might work around the issue. Alternately iterate forward using add or roll seven days at a time from the first week start as an option.

Upvotes: 1

Related Questions