溫馨提示×

如何結(jié)合Java getMonth進行日期計算

小樊
81
2024-09-14 10:18:50
欄目: 編程語言

在Java中,你可以使用java.time包中的類和方法來執(zhí)行日期計算

import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;

public class DateCalculation {
    public static void main(String[] args) {
        // 獲取當(dāng)前日期
        LocalDate currentDate = LocalDate.now();
        System.out.println("當(dāng)前日期: " + currentDate);

        // 獲取當(dāng)前月份
        int currentMonth = currentDate.getMonthValue();
        System.out.println("當(dāng)前月份: " + currentMonth);

        // 計算下個月的同一天
        LocalDate nextMonthSameDay = currentDate.plusMonths(1);
        System.out.println("下個月的同一天: " + nextMonthSameDay);

        // 計算上個月的同一天
        LocalDate previousMonthSameDay = currentDate.minusMonths(1);
        System.out.println("上個月的同一天: " + previousMonthSameDay);

        // 計算當(dāng)前月份的第一天
        LocalDate firstDayOfCurrentMonth = currentDate.with(TemporalAdjusters.firstDayOfMonth());
        System.out.println("當(dāng)前月份的第一天: " + firstDayOfCurrentMonth);

        // 計算當(dāng)前月份的最后一天
        LocalDate lastDayOfCurrentMonth = currentDate.with(TemporalAdjusters.lastDayOfMonth());
        System.out.println("當(dāng)前月份的最后一天: " + lastDayOfCurrentMonth);
    }
}

這個示例展示了如何使用java.time包中的類和方法來獲取當(dāng)前日期、月份以及計算下個月和上個月的同一天。此外,它還演示了如何計算當(dāng)前月份的第一天和最后一天。你可以根據(jù)需要修改這些示例以適應(yīng)你的具體需求。

0