【发布时间】:2014-11-24 14:48:58
【问题描述】:
我正在使用一种根据给定日期字符串计算下周一的方法。
public static String getStartOfNextWeek(String DATE){
String format = "dd.MM.yyyy";SimpleDateFormat df = new SimpleDateFormat(format);
Date date = null;
try {
date = df.parse(DATE);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int week = cal.get(Calendar.WEEK_OF_YEAR);
int year = cal.get(Calendar.YEAR);
Calendar calendar = new GregorianCalendar();
calendar.clear();
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.WEEK_OF_YEAR, week);
//add 8 days to get next weeks Monday
calendar.add(Calendar.DAY_OF_WEEK, 8);
Date startDate = calendar.getTime();
SimpleDateFormat df2 = new SimpleDateFormat("dd.MM.yyyy");
String start = df2.format(startDate);
return start;
这个工作在一个日历年中非常好,但是当我传递一个跨越两个日历年的值时会出现问题。
例如:
input: 15.12.2014
output: 22.12.2014 CORRECT
input: 22.12.2014
output: 29.12.2014 CORRECT
input: 29.12.2014
output: 6.1.2014 INCORRECT
我知道错误的位置,因为它将 WEEK_OF_YEAR 作为“1”,但将 YEAR 作为“2014”,所以输出在技术上是正确的。对我的目的来说是错误的。
我如何最好地告诉日历对象我想要第 1 周的下一个星期一,但 2015 年?
【问题讨论】:
-
Get first Monday after certain date? 和 this 和 this 和 this 和许多其他的可能重复。提示:Joda-Time。
-
您的输出中的日期也是错误的,而不仅仅是年份。 2014-12-29 之后的第一个星期一是 2015-01-05(不是第 6 个)。
-
Basil,仔细观察 - 它从 29.12.2014 开始返回 6.1.**2014** 作为下周一,这实际上是不正确的。