Find the exact difference between two (Joda Time) DateTime objects in java

I am given two dates (one of which is the present) and need to find the difference between the two. My code is giving me bad output (sometimes even negative).

I have tried using the Months, Days, Seconds, Hours, and Years classes and appropriate between methods with no luck.

Edit: Went back to my original code but without Duration. @Basil Bourque posted a great solution but I just don't have enough experience with Periods/Duration and all that to format dynamically from them.

Solution

public static String formattedTime(DateTime d){
    DateTime present = new DateTime(Calendar.getInstance());

    //dont really want to deal with WHY its 7hrs ahead. o well
    DateTime date = d.minusHours(7);

    int diff = Seconds.secondsBetween(date,present).getSeconds();
    String postfix = "s";
    Log.i("time", "" + diff);

    if(diff>59){
        diff = Minutes.minutesBetween(date, present).getMinutes();
        postfix = "s";
        if(diff>59){
            diff = Hours.hoursBetween(date, present).getHours();
            postfix = "hr";
            if(diff>1)
                postfix+="s";
            if(diff>23){
                diff = Days.daysBetween(date, present).getDays();
                postfix = "d";
                if(diff>6){
                    diff = Weeks.weeksBetween(date, present).getWeeks();
                    postfix = "wk";
                    if(diff>1)
                        postfix+="s";
                    if(diff>3){
                        diff = Months.monthsBetween(date, present).getMonths();
                        postfix = "m";
                        if(diff>11){
                            diff = Years.yearsBetween(date, present).getYears();
                            postfix = "yr";
                            if(diff>1)
                                postfix+="s";
                        }
                    }
                }
            }
        }
    }
    return diff+postfix;
}

You are working too hard. You are using the wrong class for your purpose.

Period Class

In Joda-Time, use the Period class when you want to represent a span of time as a number of years, months, days, hours, minutes, seconds. Joda-Time represents a span of time in any of three ways: Interval , Duration , or Period .

Joda-Time follows the ISO 8601 standard for parsing and generating string representations of the date-time values. For Period that means the PnYnMnDTnHnMnS format where P marks the beginning while the T separates the year-month-day portion from the hour-minute-second portion. A half-hour is PT30M . P3Y6M4DT12H30M5S represents "three years, six months, four days, twelve hours, thirty minutes, and five seconds". Search StackOverflow.com for more info and examples.

Look at the PeriodFormatter and PeriodFormatterBuilder classes if you want to pretty-print with words.

You can also ask the Period object for the various component numbers if you need the integers.

Time Zone

Also, you should specify a time zone. If omitted then your JVM's current default time zone is applied implicitly. Better to specify explicitly the time zone you desire/expect.

Always use proper time zone names, never the 3-4 letter codes. Those codes are neither standardized nor unique. And they further confuse the issue of Daylight Saving Time (DST).

Furthermore, commonly servers are kept on UTC time zone. Usually best to do nearly all of your business logic, data storage, data exchange, and logging in UTC.

Example Code

Note that you can ask DateTime for current moment without involving a java.util.Date object (as seen in your Question).

Example code for Period.

DateTimeZone zone = DateTimeZone.forID( "America/Detroit" ) ;
DateTime then = new DateTime( yourJUDate , zone ) ;
DateTime now = DateTime.now( zone ) ;
Period period = new Period( then , now ) ;

你可以在这里看到答案:两个日期之间的天数,并用你想要的单位进行调整。


使两个字符串相互比较,您可以使用String#split()方法分割它以查明年/月/日等。

链接地址: http://www.djcxy.com/p/36668.html

上一篇: 计算时代以来多少小时?

下一篇: 在java中查找两个(Joda Time)DateTime对象之间的确切区别