我想获取给定日期一周的最后一周和第一周。 例如,如果日期是 2011 年 10 月 12 日,那么我需要 2011 年 10 月 10 日(作为一周的开始日期)和 2011 年 10 月 16 日(作为一周的结束日期) 有谁知道如何使用日历类 (java.util.Calendar) 获取这两个日期 非常感谢!
最佳答案
一些代码如何使用 Calendar
对象。我还应该提到 joda time library因为它可以帮助您解决许多 Date/Calendar
问题。
代码
public static void main(String[] args) {
// set the date
Calendar cal = Calendar.getInstance();
cal.set(2011, 10 - 1, 12);
// "calculate" the start date of the week
Calendar first = (Calendar) cal.clone();
first.add(Calendar.DAY_OF_WEEK,
first.getFirstDayOfWeek() - first.get(Calendar.DAY_OF_WEEK));
// and add six days to the end date
Calendar last = (Calendar) first.clone();
last.add(Calendar.DAY_OF_YEAR, 6);
// print the result
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(df.format(first.getTime()) + " -> " +
df.format(last.getTime()));
}
关于java - 使用java日历类获取一周的开始和结束日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7645178/