JAVA计算日期,时间差的几种方法
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
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 (这里去下载:/)
程序代码
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 = LISECONDS.toSeconds(diff) % 60; long diffMinutes = LISECONDS.toMinutes(diff) % 60; long diffHours = LISECONDS.toHours(diff) % 24; long diffDays = LISECONDS.toDays(diff);
文章参考:/article/java/361.htm。