Skip to content Skip to sidebar Skip to footer

How To Remove The Seconds Field From A Dateformat

I want to print a time without seconds in the default format for the locale. So I get the formatter with getTimeInstance() or getTimeInstance(int style). But even when I use a SHOR

Solution 1:

DateFormat.getTimeInstance(DateFormat.SHORT) works perfectly fine here: from 20:00:00 to 20:00 and from 8:00:00 PMto 8:00 PM.

Solution 2:

EDIT: This is insufficient (as stated by the first comment below). I'm keeping this here for the sake of history and to keep others from responding in a similar fashion :)


Have you considered saving the current format as a string and manually removing the seconds using String's substring method?

Solution 3:

In case someone is reading this and either uses Java 8 or later or is fine with a (good and futureproof) external library:

    DateTimeFormatter noSeconds = DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT)
            .withLocale(Locale.ITALY);
    LocalTime time = LocalTime.now(ZoneId.systemDefault());
    System.out.println(time.format(noSeconds));

This just printed:

15.26

Please substitute your desired locale instead of Locale.ITALY. Use Locale.getDefault() for your JVM’s locale setting. I believe it prints without seconds in all locales.

In the code I have used a LocalTime object, but the same code works for many other date and time classes including LocalDateTime, OffsetDateTime, OffsetTime and ZonedDateTime.

To use DateTimeFormatter and any of the other classes mentioned on Android you need the ThreeTenABP. More details on how to in this question: How to use ThreeTenABP in Android Project. For any non-Android Java 6 or 7, use ThreeTen Backport.

Post a Comment for "How To Remove The Seconds Field From A Dateformat"