在 Java 中获取当前周
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34811395/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get the current week in Java
提问by Simon M.
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
我想获得给定日期的当前周,例如,如果日期是2016/01/19
,结果将是: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 questionbut I have an error on this line :
我已经从这个问题中获取了这段代码,但我在这一行有一个错误:
Date date = df.parse(input);
unhandled exception type ParseException
未处理的异常类型 ParseException
采纳答案by Jan
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 catchParseException
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)
你需要以某种方式抓住ParseException
并处理它。这可能意味着返回一个“默认”数字(在这种情况下为 0)或传递异常(通过在您的方法上声明抛出)
回答by Rozart
Use Java 8 LocalDate
and WeekFields
:
使用 Java 8LocalDate
和WeekFields
:
private int getCurrentWeek() {
LocalDate date = LocalDate.now();
WeekFields weekFields = WeekFields.of(Locale.getDefault());
return date.get(weekFields.weekOfWeekBasedYear());
}