当前位置:编程学习 > JAVA >>

Java计算日期和时间差

这篇文章将使用两个例子计算两个日期的时间差。
1.使用Java SDK。
2.使用Joda库。
1.使用Java SDK
 计算两个Date之间的时间差,基本思路为把Date转换为ms(微秒),然后计算两个微秒时间差。时间的兑换规则如下:
 
1s秒 = 1000ms毫秒 1min分种 = 60s秒 1hours小时 = 60min分钟 1day天 = 24hours小时
package com.qiyadeng.date;
 
import java.text.SimpleDateFormat;
import java.util.Date;
 
public class DateDifferentExample {
    public static void main(String[] args) {
        String dateStart = "2013-02-19 09:29:58";
        String dateStop = "2013-02-20 11:31:48";
 
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 
        Date d1 = null;
        Date d2 = null;
 
        try {
            d1 = format.parse(dateStart);
            d2 = format.parse(dateStop);
 
            //毫秒ms
            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("两个时间相差:");
            System.out.print(diffDays + " 天, ");
            System.out.print(diffHours + " 小时, ");
            System.out.print(diffMinutes + " 分钟, ");
            System.out.print(diffSeconds + " 秒.");
 
        } catch (Exception e) {
            e.printStackTrace();
        }
 
    }
}
运行结果:
 
两个时间相差:1 天, 2 小时, 1 分钟, 50 秒.
2.Joda时间库
 
package com.qiyadeng.date;
 
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 = "2013-02-19 09:29:58";
        String dateStop = "2013-02-20 11:31:48";
 
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd 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("两个时间相差:");
            System.out.print(Days.daysBetween(dt1, dt2).getDays() + " 天, ");
            System.out.print(Hours.hoursBetween(dt1, dt2).getHours() % 24
                    + " 小时, ");www.zzzyk.com
            System.out.print(Minutes.minutesBetween(dt1, dt2).getMinutes() % 60
                    + " 分钟, ");
            System.out.print(Seconds.secondsBetween(dt1, dt2).getSeconds() % 60
                    + " 秒.");
 
        } catch (Exception e) {
            e.printStackTrace();
        }
 
    }
}
运行结果:
 
两个时间相差:1 天, 2 小时, 1 分钟, 50 秒.
 
补充:软件开发 , Java ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,