在 Java 中计算日期/时间差
在 Java 中,您可以通过将两个日期解析为 Date 对象来确定它们之间的时间差使用 getTime() 方法。
这是计算两个时间之间差异的代码片段日期:
import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.concurrent.TimeUnit; class DateTimeDifference { public static void main(String[] args) { String dateStart = "11/03/14 09:29:58"; String dateStop = "11/03/14 09:33:43"; // Custom date format SimpleDateFormat format = new SimpleDateFormat("yy/MM/dd HH:mm:ss"); Date d1 = null; Date d2 = null; try { d1 = format.parse(dateStart); d2 = format.parse(dateStop); } catch (ParseException e) { e.printStackTrace(); } // Get the difference in milliseconds long diff = d2.getTime() - d1.getTime(); // Convert milliseconds to seconds using TimeUnit long seconds = TimeUnit.MILLISECONDS.toSeconds(diff); long minutes = TimeUnit.MILLISECONDS.toMinutes(diff); System.out.println("Time in seconds: " + seconds + " seconds."); System.out.println("Time in minutes: " + minutes + " minutes."); // Note: Java does not have a built-in method to directly calculate the difference in hours. // You can obtain the hours value by performing manual calculations. } }
使用提供的输入运行时的输出:
Time in seconds: 45 seconds. Time in minutes: 3 minutes.
以上是如何在 Java 中计算两个日期和时间之间的差异?的详细内容。更多信息请关注PHP中文网其他相关文章!