Search code examples
javagregorian-calendar

Bad week of year in Java


I have problem with correct week of year. I have JTextField, where I enter date in format DD.MM.YYYY.

private void buttonAddCulturalActionActionPerformed(java.awt.event.ActionEvent evt) {                                               
    String date = textfieldDateOfEvent.getText();
    if (!isCorrectFormatDate(date)) {
        textareaExtract.append("Wrong date format!\n");
        return;
    }
    int day = Integer.parseInt(date.substring(0, 2));
    int month = Integer.parseInt(date.substring(3, 5));
    int year = Integer.parseInt(date.substring(6, 10));
    GregorianCalendar enteredDate = new GregorianCalendar(year, month, day);
    String actionName = textfieldActionName.getText();
    String placeActionName = textfieldPlaceActionName.getText();
    int startHourAction = Integer.parseInt(textfieldStartHourAction.getText());

    if (isAllEntered(actionName, enteredDate, placeActionName, startHourAction)) {
        CulturalAction newAction = new CulturalAction(actionName, enteredDate,
                placeActionName, startHourAction);
        // culturalActions is priority queue
        culturalActions.add(newAction);
        extractAction(newAction);
    } else {
        textareaExtract.append("You need entered all parameters!\n");
    }
}

Here I set the cultural action (in constructor):

public CulturalAction(String nameAction, GregorianCalendar dateAction, String placeAction, int startHourAction) {
    this.nameAction = nameAction;
    this.placeAction = placeAction;
    this.startHourAction = startHourAction;
    // I have private attribute numberOfWeek in class CulturalAction
    cisloTydne = dateAction.get(GregorianCalendar.WEEK_OF_YEAR);
}

When I entered date 10.10.2013 and it would return the week number 45, but 40 is properly. I'm from Czech Republic.

Thank you for advices!


Solution

  • This is the problem:

    GregorianCalendar enteredDate = new GregorianCalendar(year, month, day);
    

    That's going to be calling new GregorianCalendar(2013, 10, 10) - which means November, not October.

    From the GregorianCalendar constructor docs:

    month - the value used to set the MONTH calendar field in the calendar. Month value is 0-based. e.g., 0 for January.

    Two other bits of advice:

    • If you have to use just the Java libraries, use SimpleDateFormat to perform the parsing, rather than doing it yourself
    • If you possibly can, use Joda Time instead, which is a much more sensible API