One way to do it is to create a java.time.format.DateTimeFormatter
, indicating the format to be used:
private static DateTimeFormatter FMT = DateTimeFormatter.ofPattern("HH:mm");
public String toString() {
System.out.println("Hora entrada: " + FMT.format(getHoraEntrada()) +
"\nHora saída: " + FMT.format(getHoraSaida()));
}
"HH:mm"
indicates the format: HH
are the hours (from 0 to 23) and mm
are minutes (from 0 to 59), both with a left zero if the value is less than 10. See documentation to know all possible formats.
Like the classes of java.time
are immutable and thread-safe, you can create the DateTimeFormatter
as a static field of your class, for example (as done above), so you don’t need to create a new one each time you need to format the date.
Another detail is that to create a LocalDateTime
containing the current date and time, you do not need to use a getter for each field and then build another instance with these values. In your case just do:
data1 = LocalDateTime.now();
Although in your code you did not set the seconds or fractions of a second, then the result of the method of
will be a LocalDateTime
with these fields set to zero. If that was your intention, you can truncate these values in a simpler way:
data1 = LocalDateTime.now().truncatedTo(ChronoUnit.MINUTES);
This way, the seconds and fractions of a second will be zero (the same result you would get using the method of
the way you used - without passing the values of these fields).
The java.time.temporal.ChronoUnit
indicates for the method truncatedTo
that the smaller units indicated will be zero. How I passed ChronoUnit.MINUTES
, units smaller than minutes (in this case, seconds and fractions of seconds) will be zero (but if that’s not what you wanted and you only need the current date and time, use now()
and ready).
Another tip not directly related to the problem: What is the function of the method toString()
?
Please click on [Edit] and put the code as text. Putting it as an image is not ideal, understand the reasons reading the FAQ.
– hkotsubo