简体   繁体   English

找到java中两个(Joda Time)DateTime对象之间的确切差异

[英]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. 我已经尝试过使用Months,Days,Seconds,Hours和Years类,并且在没有运气的方法之间使用。

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. @Basil Bourque发布了一个很好的解决方案,但我对Periods / Duration以及从它们动态格式化的所有方面都没有足够的经验。

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 Period

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中,如果要将时间范围表示为年,月,日,小时,分钟,秒数,请使用Period类。 Joda-Time represents a span of time in any of three ways: Interval , Duration , or Period . Joda-Time以三种方式中的任何一种表示时间跨度: IntervalDurationPeriod

Joda-Time follows the ISO 8601 standard for parsing and generating string representations of the date-time values. Joda-Time遵循ISO 8601标准,用于解析和生成日期时间值的字符串表示。 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. 对于期间,这意味着PnYnMnDTnHnMnS格式,其中P标记开头,而T将年 - 月 - 日部分与小时 - 分 - 秒部分分开。 A half-hour is PT30M . 一个半小时是PT30M P3Y6M4DT12H30M5S represents "three years, six months, four days, twelve hours, thirty minutes, and five seconds". P3Y6M4DT12H30M5S代表“三年,六个月,四天,十二小时,三十分钟和五秒”。 Search StackOverflow.com for more info and examples. 搜索StackOverflow.com以获取更多信息和示例。

Look at the PeriodFormatter and PeriodFormatterBuilder classes if you want to pretty-print with words. 如果要使用单词进行漂亮打印,请查看PeriodFormatterPeriodFormatterBuilder类。

You can also ask the Period object for the various component numbers if you need the integers. 如果需要整数,也可以向Period对象询问各种组件编号。

Time Zone 时区

Also, you should specify a time zone. 此外,您应指定时区。 If omitted then your JVM's current default time zone is applied implicitly. 如果省略,则隐式应用JVM的当前默认时区。 Better to specify explicitly the time zone you desire/expect. 最好明确指定您希望/期望的时区。

Always use proper time zone names , never the 3-4 letter codes. 始终使用正确的时区名称 ,从不使用3-4个字母代码。 Those codes are neither standardized nor unique. 这些代码既不标准也不独特。 And they further confuse the issue of Daylight Saving Time (DST). 他们进一步混淆了夏令时(DST)的问题。

Furthermore, commonly servers are kept on UTC time zone. 此外,通常服务器保持在UTC时区。 Usually best to do nearly all of your business logic, data storage, data exchange, and logging in UTC. 通常最好做几乎所有业务逻辑,数据存储,数据交换和UTC记录。

Example Code 示例代码

Note that you can ask DateTime for current moment without involving a java.util.Date object (as seen in your Question). 请注意,您可以在不涉及java.util.Date对象的情况下询问DateTime当前时刻(如问题中所示)。

Example code for Period. 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()方法将其拆分以查找年/月/日等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM