如何从给定日期生成N个周数 - java

时间:2015-07-13 10:47:50

标签: java date weekday

我正在尝试从指定日期创建N周,而周列表应排除属于该周的周。

例如,如果我给出今天的日期,那么我想生成本周不包括N个星期的一周。

下面的

是符合我目的的样本,但我也无法创建N周数,这段代码也打印当前周。

Calendar currentDate = Calendar.getInstance(Locale.US);
int firstDayOfWeek = currentDate.getFirstDayOfWeek();

Calendar startDate = Calendar.getInstance(Locale.US);
startDate.setTime(currentDate.getTime());

int days = (startDate.get(Calendar.DAY_OF_WEEK) + 7 - firstDayOfWeek) % 7;
startDate.add(Calendar.DATE, -days);

Calendar endDate = Calendar.getInstance(Locale.US);
endDate.setTime(startDate.getTime());
endDate.add(Calendar.DATE, 6);

SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(df.format(startDate.getTime()) + " - " + df.format(endDate.getTime())); 

有人可以帮我这个吗?

1 个答案:

答案 0 :(得分:1)

从指定日期打印N个周数[不包括当前周]:

public static void printNWeeks(Calendar startDate, int weeks) {

    int firstDayOfWeek = startDate.getFirstDayOfWeek();
    int days = (startDate.get(Calendar.DAY_OF_WEEK) + 7 - firstDayOfWeek) % 7;
    startDate.add(Calendar.DATE, -days);

    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");

    for (int i = 1; i <= weeks; i++) {

        startDate.add(Calendar.DATE, 7); // change to 7 to -7 for back dates

        Calendar endDate = Calendar.getInstance(Locale.US);
        endDate.setTime(startDate.getTime());
        endDate.add(Calendar.DATE, 6);          

        System.out.println(df.format(startDate.getTime()) + " - "
                + df.format(endDate.getTime()));
    }
}

示例调用:

public static void main(String[] args) {        

   //From the given date
    Calendar startDate = Calendar.getInstance(Locale.US);
    startDate.set(2015, Calendar.JANUARY, 30);
    printNWeeks(startDate, 5);

    //From Current Date     
    startDate = Calendar.getInstance(Locale.US);
    printNWeeks(startDate, 5);
}