Adding days to Date periodically in Java

Christian Michael Tan :

I want to add days to the current date periodically. For example, I every 10 seconds that passes, I want to add 1 day to the date today. 08/09/2019 after 10 seconds turns to 08/10/2019...I've already got a working timer, I just dont know how to implement the adding of days part

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;
cassiomolin :

You should use java.time types instead of Date and Calendar, which are considered legacy types since Java 8.

Here's an example that may suit you:

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);
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=311194&siteId=1