【问题标题】:Calendar - Dates as per Week - Java日历 - 每周的日期 - Java
【发布时间】:2015-06-12 23:39:06
【问题描述】:
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。 我知道这是因为根据美国,一周的默认第一天是星期日,但我需要根据桌面日历 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

谁能帮帮我?

【问题讨论】:

  • 您在寻找什么样的星期编号?有很多不同的选择,但您需要真正准确了解要求。
  • 你想把星期五作为一周的开始吗?
  • 旁注:如果您使用的是 Java SE 8,请考虑使用新的日期和时间 API。否则考虑使用 Joda Time。

标签: java date


【解决方案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。

【讨论】:

    【解决方案2】:

    我编写了一个 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。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-06
      • 1970-01-01
      • 2014-07-21
      • 1970-01-01
      • 2012-07-07
      • 1970-01-01
      • 2020-08-12
      • 2019-09-01
      相关资源
      最近更新 更多