1

I have a function to return all dates for a specific week.

SimpleDateFormat sdf = new SimpleDateFormat("dd.MM");
Calendar cal = Calendar.getInstance();
cal.set(Calendar.WEEK_OF_YEAR, week);
String[] dates = new String[7];
currentlySelectedYear = String.valueOf(Calendar.getInstance().get(Calendar.YEAR));
// i = 2 because MONDAY is day two in week
for (int i = 2; i < 9; i++) {
    cal.set(Calendar.DAY_OF_WEEK, i);
    //i-2 to start the array at index 0
    dates[i - 2] = sdf.format(cal.getTime());
}

it works fine on all devices except samsung where each time the for loop is entered again after the first iteration the WEEK_OF_YEAR field in the calendar is reset to current week instead of the week set three lines above.

Is this a known bug for samsung or am I missing something?

Is there another way to do the same thing that maybe work on all devices?

Max90
  • 193
  • 2
  • 14
  • There is no such `DAY_OF_WEEK` that would have value `8`. – M. Prokhorov Nov 27 '17 at 15:06
  • Does this happen for all (or many) reasonable values of `week`? – Ole V.V. Nov 27 '17 at 17:38
  • @M.Prokhorov, you are entirely correct, but a lenient `Calendar` object won’t mind ever (to me, this is a disavantage of that class, but it can of course be exploited). – Ole V.V. Nov 27 '17 at 17:51
  • 1
    Possible workaround: set `WEEK_OF_YEAR` inside the loop instead of before the loop. Good solution: get [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP) and start using JSR-310, the modern Java date and time API also known as `java.time` instead of the outmoded `SimpleDateFormat` and `Calendar`. The modern API is so much nicer to work with. – Ole V.V. Nov 27 '17 at 18:22
  • @M.Prokhorov ah. thx. I did not know that. The weird thing is it works flawlessly on every device expect samsung where it already fails on the first date. – Max90 Nov 27 '17 at 19:00
  • 1
    @OleV.V. yes this happens for all values on three different samsung devices I tested it on. On all other devices it works flawlessly. Thx for the suggestion of ThreeTenABP. I'll give it a try – Max90 Nov 27 '17 at 19:01
  • 1
    I hope you’ll be happy with ThreeTenABP. There’s a thorough explanation of how to go about it in [this question: How to use ThreeTenABP in Android Project](https://stackoverflow.com/questions/38922754/how-to-use-threetenabp-in-android-project). – Ole V.V. Nov 27 '17 at 19:23
  • 1
    @OleV.V., lenient Calendar will not complain, that is true. However, I'm not sure if it behaves correctly under these circumstances. Certainly, seeing as there's a problem on Samsung, they clearly are using some version of Calendar class that's not well-behaved. I'd also vote for basically all of app code that uses datetime computation for more than just "get me the current system time" to be converted over to JSR-310 stuff. – M. Prokhorov Nov 28 '17 at 10:50

0 Answers0