简体   繁体   中英

add or subtract from a DateTime in Swing Java

I want to add/subtract a number of years, months, or days to or from a DateTime. Im using Jodatime for dates and this is my code :

else if (e.getSource()==calcul1){
            Date date1 = (Date) datePicker3.getDate();
            DateTime dt1 = new DateTime(date1);

            if ( ajout.isSelected()){

            dt1.plusYears((Integer)anlist.getValue());
            dt1.plusMonths((Integer)moilist.getValue());
            dt1.plusDays((Integer)jourlist.getValue());
            }
            if (soustr.isSelected()){
                dt1.minusYears((Integer)anlist.getValue());
                dt1.minusMonths((Integer)moilist.getValue());
                dt1.minusDays((Integer)jourlist.getValue());
            }
            DateTimeFormatter formatter = DateTimeFormat.forPattern("EEEE dd MMMM yyyy");
            textdate.setText(formatter.print(dt1));
        }

The problem is that I always get the date of today in the JTextField, what shows that my datetime is not changing despite the operations of adding and subtracting.

The addition and subtraction methods return a new DateTime. Try this:

else if (e.getSource()==calcul1){
        Date date1 = (Date) datePicker3.getDate();
        DateTime dt1 = new DateTime(date1);

        if ( ajout.isSelected()){

        dt1 = dt1.plusYears((Integer)anlist.getValue());
        dt1 = dt1.plusMonths((Integer)moilist.getValue());
        dt1 = dt1.plusDays((Integer)jourlist.getValue());
        }
        if (soustr.isSelected()){
            dt1 = dt1.minusYears((Integer)anlist.getValue());
            dt1 = dt1.minusMonths((Integer)moilist.getValue());
            dt1 = dt1.minusDays((Integer)jourlist.getValue());
        }
        DateTimeFormatter formatter = DateTimeFormat.forPattern("EEEE dd MMMM yyyy");
        textdate.setText(formatter.print(dt1));
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM