2

I want to get the current week with a given date, e.g if the date is 2016/01/19, the result will be : week number: 3

I've seen some questions and answers about this but I'm not able to achieve what I want. Here is what I've done :

public static int getCurrentWeek() {
    String input = "20160115";
    String format = "yyyyMMdd";
    SimpleDateFormat df = new SimpleDateFormat(format);
    Date date = df.parse(input);
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    int week = cal.get(Calendar.WEEK_OF_YEAR);

    return week;
}

I've took this code from this question but I have an error on this line :

Date date = df.parse(input); 

unhandled exception type ParseException

Community
  • 1
  • 1
Simon M.
  • 2,244
  • 3
  • 17
  • 34
  • 1
    You should declare the function can throw a `ParseException`: `public static int getCurrentWeek() throws ParseException {` – Manu Jan 15 '16 at 12:47
  • this link may help u http://stackoverflow.com/questions/16418661/java-get-week-number-from-any-date – Andy the android Jan 15 '16 at 12:47
  • Googling `java unhandled exception` will provide lots of information about this. – khelwood Jan 15 '16 at 12:49
  • The code works correctly. The ParseException is just thrown when you enter a different input than "20160115" – eztam Jan 15 '16 at 12:49
  • @Andytheandroid If you read my question I took my code from this question – Simon M. Jan 15 '16 at 12:50
  • The correct result should be week 2 not week 3. Because the first week belongs to 2015 according to ISO 8601 – eztam Jan 15 '16 at 12:53

2 Answers2

9

Use Java 8 LocalDate and WeekFields:

private int getCurrentWeek() {
    LocalDate date = LocalDate.now();
    WeekFields weekFields = WeekFields.of(Locale.getDefault());
    return date.get(weekFields.weekOfWeekBasedYear());
}
Rozart
  • 1,668
  • 14
  • 27
1

Look at this changed code:

    String input = "20160115";
    String format = "yyyyMMdd";
    try {
        SimpleDateFormat df = new SimpleDateFormat(format);
        Date date = df.parse(input);
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        int week = cal.get(Calendar.WEEK_OF_YEAR);

        System.out.println("Input " + input + " is in week " + week);
        return week;
    } catch (ParseException e) {
        System.out.println("Could not find a week in " + input);
        return 0;
    }

You need to catch ParseException and deal with it somehow. This could mean returning a "default" number (0 in this case) or passing the exception along (by declaring a throws on your method)

Jan
  • 13,738
  • 3
  • 30
  • 55