java - 使用java日历类获取一周的开始和结束日期

标签 java calendar dayofweek

我想获取给定日期一周的最后一周和第一周。 例如,如果日期是 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/

相关文章:

java - 取消子项目中父项目的 Maven 排除

java - 如何从 Java 运行 Windows 命令

iphone - 如何以编程方式在 iPhone 上创建将同步到 iCal 的新日历

android - 如何通过 Android 应用程序编辑日历事件

java - 如何检查一天是否位于范围之间?

javascript - Date.getDay 函数返回错误值

java - setText ("test") 正在卡住 UI

java - 更换 Xstream 设施

java - 如何在 SharedPreferences 中保存和检索日期

java - 如何从 hsqldb 中的日期检索当前日期和 day_of_month 以列出即将到来的生日