JAVA计算日期,时间差的几种方法

时间:2022-10-07 06:57:16 阅读: 最新文章 文档下载
说明:文章内容仅供预览,部分内容可能不全。下载后的文档,内容与下面显示的完全一致。下载之前请确认下面内容是否您想要的,是否完整无缺。
1. 手工计算

2.采用一个三方的jar(Joda time library) 3. 利用TimeUnit(java.util.concurrent 包中) 方法一:手工计算 程序代码

import java.text.SimpleDateFormat; import java.util.Date;

public class DateDifferentExample {

public static void main(String[] args) {

String dateStart = "01/14/2012 09:29:58"; String dateStop = "01/15/2012 10:31:48";

//HH converts hour in 24 hours format (0-23), day calculation SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");

Date d1 = null; Date d2 = null;

try {

d1 = format.parse(dateStart); d2 = format.parse(dateStop);

//in milliseconds

long diff = d2.getTime() - d1.getTime();

long diffSeconds = diff / 1000 % 60;

long diffMinutes = diff / (60 * 1000) % 60; long diffHours = diff / (60 * 60 * 1000) % 24; long diffDays = diff / (24 * 60 * 60 * 1000);

System.out.print(diffDays + " days, "); System.out.print(diffHours + " hours, "); System.out.print(diffMinutes + " minutes, "); System.out.print(diffSeconds + " seconds.");

} catch (Exception e) { e.printStackTrace(); }

}


}

结果为: 程序代码

1 days, 1 hours, 1 minutes, 50 seconds.

joda-time-2.1.jar (:http://joda-time.sourceforge.net/) 程序代码

import java.text.SimpleDateFormat; import java.util.Date;

import org.joda.time.DateTime; import org.joda.time.Days; import org.joda.time.Hours; import org.joda.time.Minutes; import org.joda.time.Seconds;

public class JodaDateDifferentExample {

public static void main(String[] args) {

String dateStart = "01/14/2012 09:29:58"; String dateStop = "01/15/2012 10:31:48";

SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");

Date d1 = null; Date d2 = null;

try {

d1 = format.parse(dateStart); d2 = format.parse(dateStop);

DateTime dt1 = new DateTime(d1); DateTime dt2 = new DateTime(d2);

System.out.print(Days.daysBetween(dt1, dt2).getDays() + " days, ");

System.out.print(Hours.hoursBetween(dt1, dt2).getHours() % 24 + " hours, ");

System.out.print(Minutes.minutesBetween(dt1, dt2).getMinutes() % 60 + " minutes, ");


System.out.print(Seconds.secondsBetween(dt1, dt2).getSeconds() % 60 + " seconds.");

} catch (Exception e) { e.printStackTrace(); } } }

结果为: 程序代码

1 days, 1 hours, 1 minutes, 50 seconds.

方法三: 采用TimeUnit ( java.util.concurrent包中的TimeUnit) 程序代码

long diffSeconds = diff / 1000 % 60;

long diffMinutes = diff / (60 * 1000) % 60;

程序代码

long diffSeconds = TimeUnit.MILLISECONDS.toSeconds(diff) % 60; long diffMinutes = TimeUnit.MILLISECONDS.toMinutes(diff) % 60; long diffHours = TimeUnit.MILLISECONDS.toHours(diff) % 24; long diffDays = TimeUnit.MILLISECONDS.toDays(diff);

文章参考:http://www.yihaomen.com/article/java/361.htm


本文来源:https://www.wddqw.com/doc/0a0da4def51fb7360b4c2e3f5727a5e9856a27a7.html