如果您使用基本时间点,LocalTime.of(05, 00) 和 LocalTime.of(17, 00) 您使用的是今天的时间。如果我理解正确,您想要计算相对于 最近 点的持续时间,这意味着如果晚上已经过去,如果午夜已经过去,您将计算相对于明天早上或相对于昨天晚上的时间,即当你现在的时间是早上之前。
你可以这样做:
LocalTime morning = LocalTime.of(05, 00);
LocalTime evening = LocalTime.of(17, 00);
LocalTime time = LocalTime.now();
Duration fromMorning = Duration.between(morning, time);
Duration toEvening = Duration.between(evening, time);
if(fromMorning.isNegative()) toEvening=toEvening.plusDays(1);
else if(!toEvening.isNegative()) fromMorning=fromMorning.minusDays(1);
System.out.println(format(fromMorning, "morning"));
System.out.println(format(toEvening, "evening"));
使用以下辅助方法:
private static String format(Duration d, String event) {
long s=d.getSeconds();
String prep=" since ";
if(s<0) { s=-s; prep=" to "; }
long h=s/3600, min=s/60;
s-=min*60; min-=h*60;
return h+" hour(s), "+min+" min, "+s+" sec"+prep+event;
}
如果您想更新时间,您的程序需要重新计算这些值并使用适当的显示技术来显示更新的值。例如。一个简单的基于swing 的应用程序可能如下所示:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionListener;
import java.time.Duration;
import java.time.LocalTime;
import javax.swing.*;
public class Clock {
public static void main(String... arg) {
EventQueue.invokeLater(Clock::openGUI);
}
static void openGUI()
{
try{ UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); }
catch(Exception ex){}// not mandatory
JFrame frame=new JFrame("Clock");
JLabel l1=new JLabel(), l2=new JLabel();
ActionListener updater=ev->{
LocalTime morning = LocalTime.of(05, 00);
LocalTime evening = LocalTime.of(17, 00);
LocalTime time = LocalTime.now();
Duration fromMorning = Duration.between(morning, time);
Duration toEvening = Duration.between(evening, time);
if(fromMorning.isNegative()) toEvening=toEvening.plusDays(1);
else if(!toEvening.isNegative()) fromMorning=fromMorning.minusDays(1);
l1.setText(format(fromMorning, "morning"));
l2.setText(format(toEvening, "evening"));
};
updater.actionPerformed(null);
frame.getContentPane().add(l1, BorderLayout.NORTH);
frame.getContentPane().add(l2, BorderLayout.SOUTH);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
new Timer(1000, updater).start();
}
private static String format(Duration d, String event) {
long s=d.getSeconds();
String prep=" since ";
if(s<0) { s=-s; prep=" to "; }
long h=s/3600, min=s/60;
s-=min*60; min-=h*60;
return h+" hour(s), "+min+" min, "+s+" sec"+prep+event;
}
}