0

I implemented the following method:

    private int getWeek(String datum){

    SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyyy");
    Date date = null;
    try {
        date = format.parse(datum);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone( "Europe/Berlin" ));
    calendar.setTime(date);

    int week = calendar.get(Calendar.WEEK_OF_YEAR);
    return week;
}

But when I call the method with

getWeek("01.01.2017") 

it returns 52. But it should be 1. Where is my mistake?

When i call the method with

getWeek("01.01.2016")

it returns 53.

sHarivaRi
  • 83
  • 1
  • 1
  • 9

2 Answers2

0

you have lost set the TimeZone in SimpleDateFormat, for example:

private int getWeek(String datum) {
    TimeZone zone = TimeZone.getTimeZone("Europe/Berlin");
    SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyyy");

    //     v--- set the timezone here 
    format.setTimeZone(zone);

    Date date = null;
    try {
        date = format.parse(datum);
    } catch (ParseException e) {
        e.printStackTrace();
    }

    Calendar calendar = Calendar.getInstance(zone);
    calendar.setTime(date);

    int week = calendar.get(Calendar.WEEK_OF_YEAR);
    return week;
}
holi-java
  • 29,655
  • 7
  • 72
  • 83
0

Damnit.. that was a huge brain failure. 52 is the correct answer for the input.

in Germany the first Week of Year is the first week with 4 or more days in the new year.

Sorry.

sHarivaRi
  • 83
  • 1
  • 1
  • 9