Convert String to Joda LocalTime format (HH:mm:ss) and Remove milliseconds

社会主义新天地 提交于 2019-12-19 18:24:06

问题


DateTimeFormatter fmt = DateTimeFormat.forPattern("HH:mm:ss");
LocalTime localTime = fmt.parseLocalTime("02:51:20");
System.out.println("LocalTime:            "+localTime);

I need only 02:51:20 but it outputs as 02:51:20.000. Is there any way that I can remove the .000 (milliseconds) from the output.


回答1:


Yes - you just need to format when you print out. Currently you're just using the default toString() representation. If you're happy with the formatter you've already got, you can just use:

System.out.println("LocalTime:            " + fmt.print(localTime));



回答2:


You can easily use your DateTimeFormetter print() method. Try like this;

    DateTimeFormatter fmt = DateTimeFormat.forPattern("HH:mm:ss");
    LocalTime localTime = fmt.parseLocalTime("02:51:20");
    System.out.println("LocalTime                        :  " + localTime);
    System.out.println("LocalTime with DateTimeFormatter :  " + fmt.print(localTime));

And the output is;

LocalTime                        :  02:51:20.000
LocalTime with DateTimeFormatter :  02:51:20



回答3:


Fixed this using

DateTime time = new DateTime();
DateTimeFormatter format = DateTimeFormat.forPattern("HH:mm:ss");
String localTime = time != null ? format.print(new LocalTime(time.getHourOfDay(), 
time.getMinuteOfHour(), time.getSecondOfMinute())) : null;

DateTime and LocalTime are from joda



来源:https://stackoverflow.com/questions/27989498/convert-string-to-joda-localtime-format-hhmmss-and-remove-milliseconds

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