Search code examples
javajava-timelocaldatelocaldatetime

How to format LocalDateTime with minutes only (truncate seconds)?


I have LocalDateTime values and want to make use of the ISO_LOCAL_DATE_TIME constant to print only up to the minutes.

Both testcases fail with:

Expected :2020-10-10T15:16
Actual   :2020-10-10T15:16:00

But why?

assertEquals("2020-10-10T15:16", LocalDateTime.parse("2020-10-10T15:16:17")
                .truncatedTo(ChronoUnit.MINUTES)
                .format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));

assertEquals("2020-10-10T15:16", DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(
        LocalDateTime.parse("2020-10-10T15:16:17").truncatedTo(ChronoUnit.MINUTES)));

Beside that: where is the difference between using the first or second approach to format a LocalDateTime value?


Solution

  • You do not need a formatter for your use case

    The LocalDateTime#toString by default omits second-of-minute and nano-of-second fields if they are zero.

    The format used will be the shortest that outputs the full value of the time where the omitted parts are implied to be zero.

    LocalDateTime#truncatedTo(ChronoUnit.MINUTES) sets the second-of-minute and nano-of-second fields to zero.

    Truncation returns a copy of the original date-time with fields smaller than the specified unit set to zero. For example, truncating with the minutes unit will set the second-of-minute and nano-of-second field to zero.

    Thus, you do not need a formatter for your use case.

    Demo:

    import java.time.LocalDateTime;
    import java.time.temporal.ChronoUnit;
    
    public class Main {
        public static void main(String[] args) {
            System.out.println(LocalDateTime.parse("2020-10-10T15:16:17").truncatedTo(ChronoUnit.MINUTES));
        }
    }
    

    Output:

    2020-10-10T15:16