import java.text.SimpleDateFormat; import java.util.Date; public class TimeDifference { public static void main(String[] args) { try { // 定义开始时间和结束时间 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date timeS = sdf.parse("2023-06-08 12:30:00"); Date timeE = sdf.parse("2023-06-08 15:45:30"); // 计算时间差 long timeDifferenceMillis = timeE.getTime() - timeS.getTime(); // 换算为时分秒 long seconds = (timeDifferenceMillis / 1000) % 60; long minutes = (timeDifferenceMillis / (1000 * 60)) % 60; long hours = (timeDifferenceMillis / (1000 * 60 * 60)); System.out.println("时间差为:" + hours + "小时 " + minutes + "分钟 " + seconds + "秒"); } catch (Exception e) { e.printStackTrace(); } } }