gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 11:19:49 31 4
gpt4 key购买 nike

我正在尝试从给定日期创建 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()));

有人可以帮我解决这个问题吗?

最佳答案

打印从给定日期起的 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);
}

关于java - 如何从给定日期生成 N 周数 - java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31381333/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com