java利用joda lib计算两个日期时间相差几天,几小时,几分钟

引入的包:

import org.joda.time.Interval;
import org.joda.time.Period;
import org.joda.time.PeriodType;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
    * 利用joda lib计算两个日期时间相差几天,几小时,几分钟
    * @param args
    */
   public static void main(String[] args) {
      SimpleDateFormat simpleDateFormat =
            new SimpleDateFormat("dd/M/yyyy hh:mm:ss");

      try {

         Date date1 = simpleDateFormat.parse("1/04/2017 11:30:10");
         Date date2 = simpleDateFormat.parse("10/5/2018 20:35:55");

         Interval interval = new Interval(date1.getTime(), date2.getTime());

         //自动计算2个日期之前的年月日,时分秒
         Period period = interval.toPeriod();

         System.out.printf(
               "%d years, %d months, %d days, %d hours, %d minutes, %d seconds%n",
               period.getYears(), period.getMonths(), period.getDays(),
               period.getHours(), period.getMinutes(), period.getSeconds());

         //指定计算2个日期之间的天数,同理可以指定想要计算的2个日期之间的年,月,日,时分秒
         period = interval.toPeriod(PeriodType.days());

         System.out.printf(
               "%d years, %d months, %d days, %d hours, %d minutes, %d seconds%n",
               period.getYears(), period.getMonths(), period.getDays(),
               period.getHours(), period.getMinutes(), period.getSeconds());

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

   }

输出结果:

1 years, 1 months, 2 days, 9 hours, 5 minutes, 45 seconds
0 years, 0 months, 404 days, 0 hours, 0 minutes, 0 seconds

你可能感兴趣的:(java利用joda lib计算两个日期时间相差几天,几小时,几分钟)