[英]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$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
要添加到什么@Karol Dowbecki回答,如果你需要用你的字符串表示LocalTime
,你可以使用DateTimeFormatter
保持一致的格式:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");
String output = localTime.format(formatter);
whiteTime = Time.valueOf(output);
這將在時間滾動時輸出00:01:00
並且不會給您錯誤
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.