帮我优化一下这段代码:public static void main(String[] args) throws Exception{ Date date = new Date(); String endTime = "2023-03-24 18:00:00"; SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); long str = date.getTime(); long end = format.parse(endTime).getTime(); while (end-str>=0){ Thread.sleep(1000); long happy = (end-str)/1000; System.out.println("距离下班还有:" + (happy/60)+"分"+(happy%60)+"秒" + " (~ ̄▽ ̄)~ "); str = new Date().getTime(); } System.out.println("下班啦!!!!!!!!!!!"); }
时间: 2023-05-26 16:01:03 浏览: 82
可以使用Java 8引入的新的时间API来替换旧的Date和SimpleDateFormat类。另外,可以使用Duration类简化计算时间差的操作。
改进后的代码如下:
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public static void main(String[] args) throws Exception{
LocalDateTime now = LocalDateTime.now();
String endTime = "2023-03-24 18:00:00";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime endDateTime = LocalDateTime.parse(endTime, formatter);
while (Duration.between(now, endDateTime).getSeconds() >= 0){
Thread.sleep(1000);
Duration duration = Duration.between(now, endDateTime);
long minutes = duration.toMinutes();
long seconds = duration.getSeconds() % 60;
System.out.println("距离下班还有:" + minutes + "分" + seconds + "秒" + " (~ ̄▽ ̄)~ ");
now = LocalDateTime.now();
}
System.out.println("下班啦!!!!!!!!!!!");
}
阅读全文