在 Java 中定期向 Date 添加天数

Adding days to Date periodically in Java

我想定期将天数添加到当前日期。 例如,我每过 10 秒,我想在今天的日期上加 1 天。 10 秒后 08/09/2019 变成 08/10/2019...我已经有了一个工作计时器,我只是不知道如何实现添加天数部分

TimerTask task = new TimerTask() {
    @Override
    public void run() {
        day = day + 1;
        model.setDay(day);
        Calendar c = Calendar.getInstance();
        if(model.getDay() ==1)
            c.setTime(date);

        Calendar d = Calendar.getInstance();
        c.add(Calendar.DAY_OF_MONTH, 1);
        d.add(Calendar.DAY_OF_MONTH, 0);

        String currentDate = dates2.format(c.getTime());
        String currentDate2 = dates2.format(d.getTime());
        model.setUpdateDate(currentDate);
        model.setUpdateDate2(currentDate2);

    }
};
Timer timer = new Timer();
long delay = 10000;
long intervalPeriod = 10000;

您应该使用 java.time types instead of Date and Calendar,自 Java 8.

以来,它们被视为 遗留类型

下面是一个可能适合您的示例:

public class CountingDays {

    private LocalDate date = LocalDate.now();

    public static void main(String[] args) {

        CountingDays countingDays = new CountingDays();

        TimerTask task = new TimerTask() {

            @Override
            public void run() {
                countingDays.date = countingDays.date.plusDays(1);
                System.out.println(countingDays.date);
            }
        };

        Timer timer = new Timer();
        long delay = 0;
        long intervalPeriod = 10_000;

        timer.schedule(task, delay, intervalPeriod);
    }
}