How to remove SECONDS field from DateFormat

I want to print the time without seconds in the default format for the locale. So I get a formatter with getTimeInstance() or getTimeInstance(int style) . But even when I use the SHORT style, it will contain the second part of the time.

Is there any way (other than creating my own format, which would then not be standard by default and manually) Can I capture by default and separate the seconds?

thanks

Roman

+4
source share
3 answers

DateFormat.getTimeInstance ( DateFormat.SHORT ) works great here: from 20:00:00 to 20:00 and from 8:00:00 to 20:00.

+14
source

EDIT : This is not enough (as indicated in the first comment below). I keep this here for the sake of history and do not allow others to respond in this way :)


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

+1
source

In case someone reads this or uses Java 8 or later or works fine with a (good and future) external library:

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

This is just printed:

 15.26 

Please replace the desired locale instead of Locale.ITALY . Use Locale.getDefault() to configure the JVM locale. I believe that it prints without seconds in all locales.

I used the LocalTime object in the LocalTime , 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 will need ThreeTenABP . Learn more about how in this question: how to use ThreeTenABP in Android Project . For any non-Android Java 6 or 7, use ThreeTen Backport .

0
source

Source: https://habr.com/ru/post/1493718/


All Articles