日历 - 每周日期 - Java

时间:2015-06-12 14:35:46

标签: java date

public static void main(String[] args) {
  int week = 1;
  int year = 2010;


  Calendar calendar = Calendar.getInstance();
  calendar.clear();
  calendar.set(Calendar.WEEK_OF_YEAR, week);
  calendar.set(Calendar.YEAR, year);


  Date date = calendar.getTime();
  System.out.println(date);
}

如果我将周,年作为输入,我会根据我们的桌面日历查找确切的开始和结束日期。 但上面的代码将输出为27th Jan, 2009, Sunday。 我知道这是因为默认的一周的第一天是按照美国的SUNDAY,但我需要根据桌面日历1st Jan, 2010, Friday作为一周的开始日期

我的要求: 如果我的输入是:

  • 周为' 1',
  • 月份为' 5',
  • 2015年'

我需要:

   1st May, 2015 --> as first day of the week
   2nd May, 2015 --> as last day of the week

如果我输入的是:

  • 周为' 1',
  • 月份为' 6',
  • 2015年'

我需要:

   1st June, 2015 --> as first day of the week
   6th June, 2015 --> as last day of the week

任何人都可以帮助我吗?

2 个答案:

答案 0 :(得分:1)

不使用CALENDAR.Week,而是使用Calendar.DAY_OF_YEAR。我刚试过它,它对我有用:

public static void main(String[] args) {
    Calendar calendar = Calendar.getInstance();
    calendar.clear();
    calendar.set(Calendar.YEAR, 2010);
    calendar.set(Calendar.DAY_OF_YEAR, 1);
    System.out.println(calendar.getTime());
    calendar.set(Calendar.DAY_OF_YEAR, 7);
    System.out.println(calendar.getTime());
}

如果你想让它在任意一周工作,只需要做一些数学计算,找出你想要的那一天。

编辑:如果您想输入一个月,也可以使用Calendar.DAY_OF_MONTH。

答案 1 :(得分:1)

我写了一个Swing日历小部件。该小部件中的一种方法计算一周中的第一天,其中一周从用户选择的一天开始,如星期五。

startOfWeek是一个带有Calendar常量的int,比如Calendar.FRIDAY。

DAYS_IN_WEEK是一个int常量,值为7.

/**
 * This method gets the date of the first day of the calendar week. It could
 * be the first day of the month, but more likely, it's a day in the
 * previous month.
 * 
 * @param calendar
 *            - Working <code>Calendar</code> instance that this method can
 *            manipulate to set the first day of the calendar week.
 */
private void getFirstDate(Calendar calendar) {
    int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK) % DAYS_IN_WEEK;
    int amount = 0;
    for (int i = 0; i < DAYS_IN_WEEK; i++) {
        int j = (i + startOfWeek) % DAYS_IN_WEEK;
        if (j == dayOfWeek) {
            break;
        }
        amount--;
    }
    calendar.add(Calendar.DAY_OF_MONTH, amount);
}

其余代码可以在我的文章Swing JCalendar Component中看到。

相关问题