How to remove the SECONDS field from a DateFormat

南楼画角 提交于 2019-12-10 15:58:33

问题


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 SHORT style it will contain the seconds part of the time as well.

Is there any way (apart from creating my own format, which then would not be the locale default and manually maintained) I can grab the default and split off the seconds ?

Thanks

Roman


回答1:


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




回答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?




回答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.



来源:https://stackoverflow.com/questions/17886532/how-to-remove-the-seconds-field-from-a-dateformat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!