Calender.set(Calender.Month, ?) 是如何工作的?
How does Calender.set(Calender.Month, ?) Work?
我正在编写一种可以将日期提前给定周数的方法。这是我的代码:
public class Date {
int year;
int month;
int day;
public Date (int year, int month, int day){
this.year = year;
this.month = month;
this.day = day;
}
public void addWeeks (int weeks){
int week = weeks * 7;
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_MONTH, this.day);
calendar.set(Calendar.MONTH, this.month);
calendar.set(Calendar.YEAR, this.year);
calendar.add(Calendar.DAY_OF_MONTH, week);
System.out.println();
System.out.println("Date after adding " + weeks + " weeks is: " + dateFormat.format(calendar.getTime()));
}
因此,如果我将今天的日期传递给年、月和日。 (03/08/2019) 然后调用 addWeeks(1) 例如,那么日期应该提前为 (03/15/2019) 但它给了我 (04/15/2019)。出于某种原因,月份总是比我输入的多 1。如果我为月份输入 2,它会给出 3,如果我输入 3,它会给出 4。
原因如下:
public static final int MONTH
: Field number for get and set indicating
the month. This is a calendar-specific value. The first month of the
year in the Gregorian and Julian calendars is JANUARY which is 0; the
last depends on the number of months in a year.
所以,你需要:
calendar.set(Calendar.MONTH, this.month-1);
Jan: 0
Feb: 1
Mar: 2
Apr: 3
May: 4
Jun: 5
Jul: 6
Aug: 7
Sep: 8
Oct: 9
Nov: 10
Dec: 11
我正在编写一种可以将日期提前给定周数的方法。这是我的代码:
public class Date {
int year;
int month;
int day;
public Date (int year, int month, int day){
this.year = year;
this.month = month;
this.day = day;
}
public void addWeeks (int weeks){
int week = weeks * 7;
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_MONTH, this.day);
calendar.set(Calendar.MONTH, this.month);
calendar.set(Calendar.YEAR, this.year);
calendar.add(Calendar.DAY_OF_MONTH, week);
System.out.println();
System.out.println("Date after adding " + weeks + " weeks is: " + dateFormat.format(calendar.getTime()));
}
因此,如果我将今天的日期传递给年、月和日。 (03/08/2019) 然后调用 addWeeks(1) 例如,那么日期应该提前为 (03/15/2019) 但它给了我 (04/15/2019)。出于某种原因,月份总是比我输入的多 1。如果我为月份输入 2,它会给出 3,如果我输入 3,它会给出 4。
原因如下:
public static final int MONTH
: Field number for get and set indicating the month. This is a calendar-specific value. The first month of the year in the Gregorian and Julian calendars is JANUARY which is 0; the last depends on the number of months in a year.
所以,你需要:
calendar.set(Calendar.MONTH, this.month-1);
Jan: 0
Feb: 1
Mar: 2
Apr: 3
May: 4
Jun: 5
Jul: 6
Aug: 7
Sep: 8
Oct: 9
Nov: 10
Dec: 11