获取Java当前周

时间:2016-01-15 12:45:18

标签: java date

我希望获得给定日期的当前周,例如,如果日期为2016/01/19,则结果为:week number: 3

我已经看到了一些关于此的问题和答案,但我无法实现我想要的。这就是我所做的:

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;
}

我从this question获取了此代码,但我在此行中出错:

Date date = df.parse(input); 

未处理的异常类型ParseException

2 个答案:

答案 0 :(得分:4)

使用Java 8 LocalDateWeekFields

private int getCurrentWeek() {
    LocalDate date = LocalDate.now();
    WeekFields weekFields = WeekFields.of(Locale.getDefault());
    return date.get(weekFields.weekOfWeekBasedYear());
}

答案 1 :(得分:0)

看看这个改变的代码:

    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;
    }

你需要抓住 ParseException并以某种方式处理它。这可能意味着返回"默认" number(在这种情况下为0)或传递异常(通过声明方法的抛出)