Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
347 views
in Technique[技术] by (71.8m points)

java - How to calculate difference between two dates in years...etc with 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();
 }

}

}

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.

When run I get:

1 years, 13 months, 0 weeks, 6 days, 1 hours, 1 minutes, 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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, ");
// ...

To prettify and get a little more control over the output, you can use a PeriodFormatterBuilder.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...