Aggiungere giorni ad un data in Java

Mattepuffo's logo
Aggiungere giorni ad un data in Java

Aggiungere giorni ad un data in Java

La gestione delle date in Java la trovo un pò prolissa; ma è comunque eseguire tutte le operazioni che vogliamo.

Ad esempio ho la necessità di aggiungere 10 giorni ad una data.

Usando DateFormat e LocalDateTime è abbastanza facile.

Ecco un esempio:

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.Locale;

public class Main {

    public static void main(String[] args) {
        String DATE_FORMAT = "yyyy-MM-dd";
        DateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT, Locale.ITALIAN);

        Date date = new Date();
        String oggi = dateFormat.format(date);
        System.out.println(oggi);

        LocalDateTime localDateTime = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
        Date currentDatePlusOneDay = Date.from(localDateTime.plusDays(10).atZone(ZoneId.systemDefault()).toInstant());

        System.out.println(dateFormat.format(currentDatePlusOneDay));
    }


}

Al metodo plusDays passate i giorni che volete aggiungere.

Se vedete la documentazione potete notare che avete anche i metodi per mesi, anni, ecc.

Enjoy!


Condividi

Commentami!