两个日期相差多少时间, 精确到秒

使用joda-time 来查询两个日期相差多少时间, 精确到秒

import java.text.ParseException;
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.Interval;
import org.joda.time.Minutes;
import org.joda.time.Period;
import org.joda.time.Seconds;

/**
 * Created by csucoderlee on 2017 10 16 10:39.
 */
public class Test2 {


    public static void test1(Date d1, Date d2) {

        // 毫秒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 + " 秒.");
        System.out.println();
    }

    public static void test2(Date d1, Date d2) throws ParseException {

        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 + " 小时 ");
        System.out.print(Minutes.minutesBetween(dt1, dt2).getMinutes() % 60 + " 分钟 ");
        System.out.print(Seconds.secondsBetween(dt1, dt2).getSeconds() % 60 + " 秒.");
        System.out.println();
    }

    public static void test3(Date d1, Date d2) {
        Interval interval = new Interval(d1.getTime(), d2.getTime());
        Period p = interval.toPeriod();
        System.out.println("时间相差:" + p.getDays() + " 天 " + p.getHours() + " 小时 " + p.getMinutes() + " 分钟" + p.getSeconds() + " 秒");
    }

    /**
     * @param args
     * @throws ParseException
     */
    public static void main(String[] args) throws ParseException {
        String dateStart = "2013-08-13 16:29:58";
        String dateStop = "2013-08-13 16:31:48";

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

        Date d1 = format.parse(dateStart);
        Date d2 = format.parse(dateStop);
        test1(d1, d2);
        test2(d1, d2);
        test3(d1, d2);
    }
}

原文,链接 

http://1985wanggang.blog.163.com/blog/static/7763833201371341545546/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值