Setting for date and time field

Asked

Viewed 174 times

0

I’m setting 2 attributes, one will be date and the other time:

@Getter
@Setter
private Date dataOcorrencia;

@Getter
@Setter
private Calendar horaOcorrencia;

I wonder if it’s the best definition for both, because it still has the class SimpleDataFormat. That’s the best definition for both?

  • 1

    This depends on what you want to do with these dates. java 8 has released a new API for dates (java.time) that I found particularly interesting. With it you could use Localdate and Localtime, with the advantage of being thread-safe (java.util.Date is not) and much simpler to use.

1 answer

0

I suggest unifying these 2 attributes in one field only, using the type originating from Java 8:

@Getter
@Setter
private LocalDateTime dhOcorrencia;

In addition to various benefits, such as immutability, fluent interface, easy manipulation (basic operations such as summation, subtraction, calculation of periods), processing of invalid dates, you will have more ease to sort by this information.

Some examples of the use of LocalDateTime:

LocalDateTime hojeAoMeioDia = LocalDate.now().atTime(12,0);

LocalTime agora = LocalTime.now();
LocalDate hoje = LocalDate.now();
LocalDateTime dataEhora = hoje.atTime(agora);


LocalDateTime dateTime = LocalDateTime.of(2014, 12, 25, 10, 30);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.