0

所以,我试图计算两个日期之间的时间差异,并以天、小时和分钟为单位输出差异。我一直在运行这个示例代码,就像一个 java 控制台应用程序一样,它工作正常,但是,当我尝试在 Android 中做同样的事情时,我得到了垃圾数据。Joda Time 对 Android 来说太复杂了吗?我应该尝试 Date4j 作为替代方案吗?

import java.util.; import org.joda.;
import org.joda.time.DateTime;

public class time {

        //(5000);
        final static long MILLIS_IN_DAY = 86400000;
        final static long MILLIS_IN_HOUR = 3600000;
        final static long MILLIS_IN_MINUTE = 60000;

    public static void main(String[] args){

        long day, hour, minute;

        //MAKE SURE TO CHECK IF USER SET(LATER)
        // DateTime(2013,9,12,0,0)
                DateTime d1 = new DateTime(2013,9,17,0,0);
                DateTime d2 = new DateTime(2013,9,12,21,30);


                //long date = d2.getMillis();

                DateTime d3 = new DateTime();

                long diffInMillis = d3.getMillis() - d1.getMillis();
                minute = (diffInMillis/MILLIS_IN_MINUTE)%60;
                hour = (diffInMillis/MILLIS_IN_HOUR)%24;
                day = (diffInMillis/MILLIS_IN_DAY);


                System.out.println(Long.toString(d1.getMillis()));
                System.out.println(Long.toString(d2.getMillis()));  

                System.out.println(Long.toString(d3.getMillis()));

                System.out.println(Long.toString(diffInMillis));

                System.out.println("Minutes:");
                System.out.println(Long.toString(minute));
                System.out.println("Hours:");
                System.out.println(Long.toString(hour));
                System.out.println("Days:");
                System.out.println(Long.toString(day));
    }
    }
4

1 回答 1

3

不要手动计算此值。用 Joda-Time 方法计算。没有理由使用Joda和不使用Joda's 方法 ,
例如DaysHoursMintes

    System.out.println("Minutes:");
    System.out.println(Minutes.minutesBetween(d2, d1).getMinutes() % 60);
    System.out.println("Hours:");
    System.out.println(Hours.hoursBetween(d2, d1).getHours() % 24);
    System.out.println("Days:");
    System.out.println(Days.daysBetween(d2, d1).getDays());  

或带句号

    Period period = new Period(d2, d1);
    System.out.println("Minutes:");
    System.out.println(period.getMinutes());
    System.out.println("Hours:");
    System.out.println(period.getHours());
    System.out.println("Days:");
    System.out.println(period.getDays());
于 2013-09-18T17:03:40.003 回答