从日期中添加和减去天

时间:2020-02-24 19:55:51

标签: java

我写了一个代码,该代码可以从日期中添加和减去天,但是它不能有效地工作。 我很难把日期的加减也算作leap年。如何使加减法有效?

添加:

public void additionOfDays(int days) {
    year += days / 365;
    days %= 365;
    month += days / 30;
    days %= 30;
    day += days;
    if (isLeapYear() && month == 2 && day > 28) {
        day -= 28;
        month++;
    } else if (ODD_MONTHS.contains(month) && day > 31) {
        day -= 31;
        month++;
    } else if (day > 30) {
        day -= 30;
        month++;
    }
}

减法:

public void subtractionOfDays(int days) {
        year -= days / 365;
        days %= 365;
        month -= days / 30;
        days %= 30;
        day -= days;
        if (isLeapYear() && month == 2 && day > 28) {
            day = 28;
            month--;
        } else if (ODD_MONTHS.contains(month) && day > 31) {
            day += 31;
            month--;
        } else if (day > 30) {
            day += 30;
            month--;
        }

月份名称和奇数月份:

public String[] MONTH_NAMES = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
    public List<Integer> ODD_MONTHS = Arrays.asList(1, 3, 5, 7, 8, 10, 12); 

1 个答案:

答案 0 :(得分:0)

检查日历类https://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html中的添加方法

编辑:

注释指出,LocalDate类是更好的选择 https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html