int month = calendar.get(Calendar.MONTH) + 1;改成获取下个月日期
时间: 2024-03-19 13:44:59 浏览: 127
你可以通过调用 `calendar.add(Calendar.MONTH, 1)` 方法来获取下个月的日期,然后再获取该日期的月份。以下是一个示例代码:
```java
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.MONTH, 1);
int nextMonth = calendar.get(Calendar.MONTH) + 1;
System.out.println("Next month's date: " + calendar.getTime());
System.out.println("Next month's month: " + nextMonth);
```
这将输出下个月的日期和月份,例如:
```
Next month's date: Sat Feb 19 16:53:17 EST 2022
Next month's month: 2
```
相关问题
int month = calendar.get(Calendar.MONTH) + 1; int day = calendar.get(Calendar.DAY_OF_MONTH); 前一天的应该怎么写
获取前一天日期的Java代码可以这样写:
```java
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_MONTH, -1);
int month = calendar.get(Calendar.MONTH) + 1;
int day = calendar.get(Calendar.DAY_OF_MONTH);
```
其中,`calendar.add(Calendar.DAY_OF_MONTH, -1)` 表示将当前日期向前推一天。这里使用 `DAY_OF_MONTH` 表示对日期进行操作,`-1` 表示向前推一天。
public static int getAge(Date birth) { Calendar cal = Calendar.getInstance(); int thisYear = cal.get(Calendar.YEAR); int thisMonth = cal.get(Calendar.MONTH); int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH); cal.setTime(birth); int birthYear = cal.get(Calendar.YEAR); int birthMonth = cal.get(Calendar.MONTH); int birthdayOfMonth = cal.get(Calendar.DAY_OF_MONTH); int age = thisYear - birthYear; // 未足月 if (thisMonth <= birthMonth) { // 当月 if (thisMonth == birthMonth) { // 未足日 if (dayOfMonth < birthdayOfMonth) { age--; } } else { age--; } } return age; }
下面是代码的简化版本:
```
public static int getAge(Date birth) {
Calendar cal = Calendar.getInstance();
cal.setTime(birth);
int birthYear = cal.get(Calendar.YEAR);
int birthMonth = cal.get(Calendar.MONTH);
int birthdayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
int thisMonth = Calendar.getInstance().get(Calendar.MONTH);
int dayOfMonth = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
int age = thisYear - birthYear;
if (thisMonth <= birthMonth && thisMonth == birthMonth && dayOfMonth < birthdayOfMonth) {
age--;
} else {
age--;
}
return age;
}
```
这个简化版本将一些变量的声明和初始化放在了一起,同时将一些重复的代码进行了简化。
阅读全文