在实际开发中,可以写成静态方法,直接调用,这里为了测试方便,使用@Test方式;
返回当前的年份
// 返回当前的年份
@Test
public void getCurrentYear() {
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
System.out.println(year);
}
测试结果:
返回当前月份
// 返回当前月份
@Test
public void getCurrentMonth() {
Calendar calendar = Calendar.getInstance();
int month = calendar.get(Calendar.MONTH) + 1;
System.out.println(month);
}
测试结果:
获取上一个月
// 获取上一个月
@Test
public void getLastMonth() {
LocalDate localDate = LocalDate.now();
localDate = localDate.minusMonths(1);
// 2022-09-19 localDate 时返回上个月的当天
System.out.println(localDate);
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMM");
// 202209 返回上个月
System.out.println(dtf.format(localDate));
}
测试结果:
获取这个月有多少天(方式一)
@Test
public void getCurrentDays() {
int month = 9;
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MONTH, month -1);
calendar.set(Calendar.DATE, 1);
calendar.roll(Calendar.DATE, -1);
int days = calendar.get(Calendar.DATE);
// 30
System.out.println(days);
}
测试结果:
获取这个月有多少天(方式二)
// 获取这个月有多少天
@Test
public void getDays() {
Date date = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
System.out.println(calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
}
测试结果:
获取某个时间月份的最后一天
// 获取某个时间月份的最后一天
@Test
public void getTimeLastDay() {
Date date = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
System.out.println(calendar.getTime());
}
测试结果: