localTime可以在java.sql.Time中连续添加1秒吗?



java.time.LocalTime中,有addSeconds()方法。 可以连续加1秒吗?

LocalTime localTime = Time.valueOf("00:00:00").toLocalTime();
localTime = localTime.plusSeconds(1L);
String output = localTime.toString();
whiteTime = Time.valueOf(output);

我添加了来自 Intellij 的这部分错误消息。

00:00:58
respond to action of white: Black Time
00:00:59
respond to action of white: Black Time
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException
at java.sql/java.sql.Time.valueOf(Time.java:109)
at ui.TimerPanel.blackTimerTikTok(TimerPanel.java:71)
at util.GameModel$2.actionPerformed(GameModel.java:87)
at java.desktop/javax.swing.Timer.fireActionPerformed(Timer.java:317)
at java.desktop/javax.swing.Timer$DoPostEvent.run(Timer.java:249)
at java.desktop/java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:313)
at java.desktop/java.awt.EventQueue.dispatchEventImpl(EventQueue.java:770)
at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:721)
at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:715)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:389)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:85)
at java.desktop/java.awt.EventQueue.dispatchEvent(EventQueue.java:740)
at java.desktop/java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:203)
at java.desktop/java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:124)
at java.desktop/java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:113)
at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:109)
at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.desktop/java.awt.EventDispatchThread.run(EventDispatchThread.java:90)

看起来它在到达00:00:59时会出错。如何使其00:01:00连续计数几秒钟?

问题是您使用的是java.sql.Time.valueOf(String)并且依赖于可能无法打印秒LocalTime.toString()格式,因为:

使用的格式将是输出省略部分暗示为零的时间的完整值的最短格式。

您应该使用Time.valueOf(LocalTime)

LocalTime localTime = Time.valueOf("00:00:59").toLocalTime();
localTime = localTime.plusSeconds(1);
System.out.println(Time.valueOf(localTime)); // 00:01:00

为了补充 Dowbecki 回答@Karol,如果您需要使用LocalTime的字符串表示形式,您可以使用DateTimeFormatter来保持格式一致:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");
String output = localTime.format(formatter);
whiteTime = Time.valueOf(output);

这将在时间滚动时输出00:01:00,而不会给您错误

最新更新