码迷,mamicode.com
首页 > 其他好文 > 详细

计算时间差工具类

时间:2016-02-14 11:37:58      阅读:426      评论:0      收藏:0      [点我收藏+]

标签:

有两种方法,1.使用Java SDK。2.使用Joda库。

使用Java SDK

package file;


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

public class time {
    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();
        }

    }
}

  使用joda 库

package time;

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

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

    }
}

  

计算时间差工具类

标签:

原文地址:http://www.cnblogs.com/JAYIT/p/5188793.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!