[英]How to generate N number of weeks from the date given - java
I am trying to create N
of weeks from the date given and the week list should exclude the week which belongs to the week. 我正在尝试从给定的日期创建N
周,并且周列表应排除属于该周的周。
for example if i give todays date then i would like to generate the week excluding this week to N
number of weeks. 例如,如果我给出今天的日期,那么我想将除本周之外的一周生成为N
个星期。
below is the sample which serves my purpose but i am not able to create the N
number of weeks also this piece of code prints the current week. 下面是满足我的目的的示例,但是我无法创建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()));
could some one help me on this? 有人可以帮我吗?
Print N number of weeks from the given date [excludes current week]: 从给定日期打印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()));
}
}
Sample Invocations: 样本调用:
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.