0
I’m trying to make the date the user enters in the constructor advanced in 1 day.
However I am not getting the expected result, is being returned the same day. I tried to check by debug and simply the plusDays()
not sum 1 day. I’m probably doing something wrong, can help me?
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Data {
private Integer dia;
private Integer mes;
private Integer ano;
private LocalDate dataHoje;
public Data(Integer dia, Integer mes, Integer ano) {
if(dia > 31 || dia <= 0) {
throw new RuntimeException("Não existem dias nulos, nem dias maiores que 31!");
} else {
setDia(dia);
}
if (mes > 12) {
throw new RuntimeException("Só existem 12 meses!");
} else if (mes <= 0) {
throw new RuntimeException("Não podem existir meses negativos ou nulos!");
}else {
setMes(mes);
}
if(ano < 0) {
throw new RuntimeException("Não trabalhamos com anos A.C! Insira um D.C");
} else {
setAno(ano);
}
this.dataHoje = LocalDate.of(ano, mes, dia);
}
public Data() {
LocalDate now = LocalDate.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
System.out.println("A Data de hoje é : " + now.format(formatter));
}
public String getDataInserida() {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
return dataHoje.format(formatter);
}
public LocalDate avancarDia() {
dataHoje.plusDays(1);
return dataHoje;
}
// aqui em baixo ficam os getters e setters dos atributos primitivos
}
This is my app class.
public class App {
public static void main(String[] args) {
Data dataSistema = new Data();
Data data = new Data(8,12,1998);
System.out.println(data.getDataInserida());
data.avancarDia();
System.out.println(data.getDataInserida());
}
}
Yes, sorry, I switched to plusDay, but forgot to change here. Your solution worked, thank you very much, did not know that they were immutable.
– Bussola
Seriously, thank you very much friend, I’m learning java now, so the difficulty with the dates, thank you very much!
– Bussola
@Bussola For immutability is true for all classes of
java.time
. I also made this same mistake the first time I used this API :-)– hkotsubo