如何使用 Joda-Time 计算两个日期之间的差异(以年为单位)...等 [英] How to calculate difference between two dates in years...etc with Joda-Time
本文介绍了如何使用 Joda-Time 计算两个日期之间的差异(以年为单位)...等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
import java.text.SimpleDateFormat;
import java.util.Date;
import org.joda.time.*;
public class Test {
public static void main(String[] args) {
String dateStart = "01/01/2000 05:30";
String dateStop = "02/2/2001 06:31";
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm");
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(Years.yearsBetween(dt1, dt2).getYears() + " years, ");
System.out.print(Months.monthsBetween(dt1, dt2).getMonths() % 52 + " months, ");
System.out.print(Weeks.weeksBetween(dt1, dt2).getWeeks() % 4 + " weeks, ");
System.out.print(Days.daysBetween(dt1, dt2).getDays() % 7 + " days, ");
System.out.print(Hours.hoursBetween(dt1, dt2).getHours() % 24 + " hours, ");
System.out.print(Minutes.minutesBetween(dt1, dt2).getMinutes() % 60 + " minutes, ");
} catch (Exception e) {
e.printStackTrace();
}
}
}
我想使用 Joda-Time 输出两个日期之间的年数、月数、周数、天数、小时数和分钟数.我的问题是我在哪里实现一个月中的周数(永远不会恒定).我也不认为我的 % 是对的.
I want to output the number of years, months, weeks, days, hours, and minutes between two dates using Joda-Time. My question is where do I implement the number of weeks in a month (which in never constant). I don't think my %'s are right either.
运行时我得到:
1 years, 13 months, 0 weeks, 6 days, 1 hours, 1 minutes,
推荐答案
Period
为您提供了开箱即用的功能.
Period
gives you this out of the box.
Period period = new Period(d1, d2);
System.out.print(period.getYears() + " years, ");
System.out.print(period.getMonths() + " months, ");
// ...
要美化并更好地控制输出,您可以使用 PeriodFormatterBuilder
.
To prettify and get a little more control over the output, you can use a PeriodFormatterBuilder
.
这篇关于如何使用 Joda-Time 计算两个日期之间的差异(以年为单位)...等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文