Java 使用 joda 的时间 datediff

Java time datediff using joda

这是我用 joda 时间计算延迟时间的代码:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.joda.time.Interval;
import org.joda.time.Period;

public class DateDiff {

    public static void main(String[] args) {

    DateDiff obj = new DateDiff();
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-DD hh:mm:ss");

    try {

        Date date1 = simpleDateFormat.parse("2015-10-01 20:32:06");
        Date date2 = simpleDateFormat.parse("2015-10-25 00:52:36");

        obj.printDifference(date1, date2);  

        } catch (ParseException e) {
        }
    }

    public void printDifference(Date startDate, Date endDate){

        Interval interval = new Interval(startDate.getTime(), endDate.getTime());
        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());
    }
}

这是我的参考资料:http://www.mkyong.com/java/java-time-elapsed-in-days-hours-minutes-seconds/ 当我 运行 我收到的代码时:

0 years, 0 months, 2 days, 4 hours, 20 minutes, 30 seconds

有人能告诉我我的代码有什么问题吗?

d 小。

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");


D   Day in year
d   Day in month

SimpleDateFormat doc

I've changed the 'DD'to 'dd' but the result remains the same

嗯,这是因为你忽略了你的某些东西Period instance: the weeks

你需要这样输出实例:

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

你会得到:

0 years, 0 months, 3 weeks, 2 days, 4 hours, 20 minutes, 30 seconds

据我所知...它看起来是正确的。


如果您不喜欢在这里使用周数,那么您可以使用不同的 PeriodType。例如:

Period period = interval.toPeriod(PeriodType.yearMonthDayTime());

这将创建一个仅使用年、月、日和时间的类型,就像您在示例中想要的那样。

那么输出是:

0 years, 0 months, 23 days, 4 hours, 20 minutes, 30 seconds

混合两个库的代码你太辛苦了:

  • java.util.DateSimpleDateFormat
  • 的旧世界
  • 乔达时间

更好的解决方案是只使用一个库,这里是 Joda-Time 的代码(因为旧世界根本不处理持续时间):

DateTimeFormatter f = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime ldt1 = LocalDateTime.parse("2015-10-01 20:32:06", f);
LocalDateTime ldt2 = LocalDateTime.parse("2015-10-25 00:52:07", f);
Period p = new Period(ldt1, ldt2, PeriodType.yearMonthDayTime());
String diff = PeriodFormat.wordBased(Locale.ENGLISH).print(p);
System.out.println(diff); // 23 days, 4 hours, 20 minutes and 1 second

与建议混合方案相比的优势:

  • 更短
  • 零分量被抑制
  • 已处理复数化(对于英语:“1 秒”与“2 秒”)
  • 列表模式支持包括单词"and"

关于格式模式的一般建议:

请始终参考库的 documentation 您可以使用哪些格式符号及其含义。阅读胜于猜测 ;-)。所有库都没有唯一的模式,但 "D" 在两个库中实际上代表 "day-of-year" 和 "d" 代表 "day-of-month"。