我是Java的新手,我正在尝试获取2009年的第7天。 我对如何处理感到困惑。下面是我的代码
public class Main {
public static void main(String[] args) {
System.out.println("WELCOME TO MY CALENDER CLASS");
Calendar calendar = Calendar.getInstance();
calendar.set(DAY_OF_MONTH,7);
calendar.set(Calendar.YEAR,2009);
for(int i =1; i <= 12; i++){
calendar.set(DAY_OF_MONTH,i);
System.out.println(calendar.getTime());
}
}
}
更新:这是我的结果
Sun Mar 01 23:41:14 GMT 2009
Mon Mar 02 23:41:14 GMT 2009
Tue Mar 03 23:41:14 GMT 2009
Wed Mar 04 23:41:14 GMT 2009
Thu Mar 05 23:41:14 GMT 2009
Fri Mar 06 23:41:14 GMT 2009
Sat Mar 07 23:41:14 GMT 2009
Sun Mar 08 23:41:14 GMT 2009
Mon Mar 09 23:41:14 GMT 2009
Tue Mar 10 23:41:14 GMT 2009
Wed Mar 11 23:41:14 GMT 2009
Thu Mar 12 23:41:14 GMT 2009
答案 0 :(得分:2)
好的,假设您从1月1日开始,这是您原因的简单示例。我希望Java1.8代码对您来说很清楚。
public static void main(String[] args) {
// create two localdate start of a year instances, one for current year and one for next year, 2009 and 2010 respectively
LocalDate thisYear = LocalDate.of(2009, Month.JANUARY, 1);
LocalDate nextYear = LocalDate.of(2010, Month.JANUARY, 1);
// used only for counting number of every seventh day in a year
int i=0;
// while we are not in the next year, 2010
while (thisYear.isBefore(nextYear)) {
i++;
// print current date
System.out.println(i+" " + thisYear.toString());
// add a week or seven days to our thisYear instance and loop thru again
thisYear = thisYear.plusWeeks(1);
}
}
答案 1 :(得分:2)
您的代码存在的问题是,在for
循环中,您为Calendar
对象设置了日期而不是月份。
因此更改为:
for(int i = 0; i < 12; i++){
calendar.set(Calendar.MONTH, i);
System.out.println(calendar.getTime());
}
循环从0开始到11,因为月份是从0开始的。
如果您可以使用LocalDate
,那么您的代码将更加简单和高效:
System.out.println("WELCOME TO MY CALENDER CLASS");
LocalDate date;
for(int i = 1; i <= 12; i++){
date = LocalDate.of(2009, Month.of(i), 7);
System.out.println(date.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL)));
}