将字符串转换为Joda LocalTime格式(HH:mm:ss)并移除毫秒部分。

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

我只需要02:51:20,但输出结果是02:51:20.000。有没有办法可以从输出中去掉.000(毫秒)?

好的,只需重用您的格式化程序进行打印,而不是解析。 - fge
嗨,谢谢你的回答,它有效。有没有办法让我得到LocalTime而不是String。我需要LocalTime为02:51:20而不是02:51:20.000。 - souashokraj
不,LocalTime.toString() 是固定的。你需要通过格式化程序来获得所需的格式。 - fge
好的。如何从LocalTime中删除毫秒。我只需要LocalTime以HH:mm:ss格式,而不包括毫秒。这可能吗? - souashokraj
等一下,我以为你说提供的解决方案有效了? - fge
是的,当我打印它时,它会从本地时间中删除 .000。但我需要以 HH:mm:ss 格式的 LocalTime 响应,其中不包含毫秒。我正在尝试将格式为 HH:mm:ss 的字符串格式化为不带毫秒的 LocalTime。这可能吗? - souashokraj
3个回答

3
您可以轻松使用您的DateTimeFormetter print()方法。请尝试以下方式:

    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));

输出结果如下:

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

3
是的 - 您只需要在打印输出时进行格式化。目前,您只是使用默认的 toString() 表示。如果您对已有的格式化程序感到满意,只需使用以下代码即可:
System.out.println("LocalTime:            " + fmt.print(localTime));

2

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接