gpt4 book ai didi

java - Calender.set(Calender.Month, ?) 如何工作?

转载 作者:行者123 更新时间:2023-11-30 05:44:39 26 4
gpt4 key购买 nike

我正在编写一种方法,可以将日期提前给定的周数。这是我的代码:

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

关于java - Calender.set(Calender.Month, ?) 如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55070978/

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