How to format minutes using Java Localdatetime

Asked

Viewed 360 times

1

I am beginner in Java and my doubt is in class LocalDateTime.

The time is recorded at a certain point in the program. When I have write on the screen, appears like this:

inserir a descrição da imagem aqui

And I need you to come up with the number 0 before the number 5, which means two decimal places.

Entering the data:

inserir a descrição da imagem aqui

Showing the data:

inserir a descrição da imagem aqui

  • 2

    Please click on [Edit] and put the code as text. Putting it as an image is not ideal, understand the reasons reading the FAQ.

1 answer

3


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()?

  • I understood and worked perfectly as I wanted. Thank you very much!! The function of the toString() method was only for testing. to see what the exit would be like.

Browser other questions tagged

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