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

Can localTime be added by 1 second continually in java.sql.Time?

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.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.run(EventQueue.java:721)
    at java.desktop/java.awt.EventQueue.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() 格式,该格式可能不会打印秒数,因为:

The format used will be the shortest that outputs the full value of the time where the omitted parts are implied to be zero.

你应该使用 Time.valueOf(LocalTime):

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

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

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");

String output = localTime.format(formatter);
whiteTime = Time.valueOf(output);

这将在时间滚动时输出 00:01:00 并且不会给你错误