如何在android中的两个日期之间取得差异?,尝试过每一件事并发布

时间:2012-05-21 18:11:57

标签: java android date time

我在这里看到了所有的帖子,但我仍然无法弄清楚如何在两个安卓日期之间找到差异。

这就是我的所作所为:

long diff = date1.getTime() - date2.getTime();
Date diffDate = new Date(diff);

我得到:日期是1970年1月1日,时间总是在两个小时内变大......我来自以色列所以两个小时是时间偏离。

我怎样才能得到正常的差异?

12 个答案:

答案 0 :(得分:73)

你接近正确的答案,你得到这两个日期之间的毫秒差异,但是当你试图用这个差异构建一个日期时,假设你要创建一个新的{{1}具有该差异值的对象作为其纪元时间。如果你正在寻找一个小时的时间,那么你只需要对Date做一些基本的算术来得到不同的时间部分:

diff

所有这些数学运算只会进行整数运算,因此会截断任何小数点

答案 1 :(得分:22)

    long diffInMillisec = date1.getTime() - date2.getTime();

    long diffInDays = TimeUnit.MILLISECONDS.toDays(diffInMillisec);
    long diffInHours = TimeUnit.MILLISECONDS.toHours(diffInMillisec);
    long diffInMin = TimeUnit.MILLISECONDS.toMinutes(diffInMillisec);
    long diffInSec = TimeUnit.MILLISECONDS.toSeconds(diffInMillisec);

答案 2 :(得分:14)

一些补充: 在这里我将字符串转换为日期,然后我比较当前时间。

String toyBornTime = "2014-06-18 12:56:50";
    SimpleDateFormat dateFormat = new SimpleDateFormat(
            "yyyy-MM-dd HH:mm:ss");

    try {

        Date oldDate = dateFormat.parse(toyBornTime);
        System.out.println(oldDate);

        Date currentDate = new Date();

        long diff = currentDate.getTime() - oldDate.getTime();
        long seconds = diff / 1000;
        long minutes = seconds / 60;
        long hours = minutes / 60;
        long days = hours / 24;

        if (oldDate.before(currentDate)) {

            Log.e("oldDate", "is previous date");
            Log.e("Difference: ", " seconds: " + seconds + " minutes: " + minutes
                    + " hours: " + hours + " days: " + days);

        }

        // Log.e("toyBornTime", "" + toyBornTime);

    } catch (ParseException e) {

        e.printStackTrace();
    }

答案 3 :(得分:2)

使用java.time.Duration

    Duration diff = Duration.between(instant2, instant1);
    System.out.println(diff);

这将打印类似

的内容
PT109H27M21S

这意味着一段时间为109小时27分21秒。如果你想要更具人性化的东西 - 我会先给出9版本,这是最简单的:

    String formattedDiff = String.format(Locale.ENGLISH,
            "%d days %d hours %d minutes %d seconds",
            diff.toDays(), diff.toHoursPart(), diff.toMinutesPart(), diff.toSecondsPart());
    System.out.println(formattedDiff);

现在我们得到

4 days 13 hours 27 minutes 21 seconds

Duration类是现代Java日期和时间API java.time的一部分。这是捆绑在较新的Android设备上。在旧设备上,获取ThreeTenABP并将其添加到项目中,并确保从同一个包中导入org.threeten.bp.Duration和其他日期时间类。

假设您还没有Java 9版本,您可以依次减去较大的单位以获得较小的单位:

    long days = diff.toDays();
    diff = diff.minusDays(days);
    long hours = diff.toHours();
    diff = diff.minusHours(hours);
    long minutes = diff.toMinutes();
    diff = diff.minusMinutes(minutes);
    long seconds = diff.toSeconds();

然后你可以格式化上面的四个变量。

你做错了什么?

Date表示某个时间点。它从来没有意味着代表一定的时间,持续时间,并且它不适合它。尝试完成这项工作充其量会导致令人困惑且难以维护的代码。你不希望如此,所以请不要。

链接

答案 4 :(得分:2)

如果您使用Kotlin语言进行Android开发,则可以使用ExperimentalTime扩展名。要获得不同的日子,可以这样使用它:

@ExperimentalTime
fun daysDiff(c1: Calendar, c2: Calendar): Double {
    val diffInMillis = c1.timeInMillis - c2.timeInMillis
    return diffInMillis.milliseconds.inDays
}

或者如果要获取整数形式的结果:

@ExperimentalTime
fun daysDiff2(c1: Calendar, c2: Calendar): Int {
    val diffInMillis = c1.timeInMillis - c2.timeInMillis
    return diffInMillis.milliseconds.toInt(DurationUnit.DAYS)
}

答案 5 :(得分:1)

这是我基于@Ole V. V.答案的答案。

这也适用于Singular。

private String getDuration(Date d1, Date d2) {
    Duration diff = Duration.between(d1.toInstant(), d2.toInstant());


    long days = diff.toDays();
    diff = diff.minusDays(days);
    long hours = diff.toHours();
    diff = diff.minusHours(hours);
    long minutes = diff.toMinutes();
    diff = diff.minusMinutes(minutes);
    long seconds = diff.toMillis();

    StringBuilder formattedDiff = new StringBuilder();
    if(days!=0){
        if(days==1){
            formattedDiff.append(days + " Day ");

        }else {
            formattedDiff.append(days + " Days ");
        }
    }if(hours!=0){
        if(hours==1){
            formattedDiff.append(hours + " hour ");
        }else{
            formattedDiff.append(hours + " hours ");
        }
    }if(minutes!=0){
        if(minutes==1){
            formattedDiff.append(minutes + " minute ");
        }else{
            formattedDiff.append(minutes + " minutes ");
        }
    }if(seconds!=0){
        if(seconds==1){
            formattedDiff.append(seconds + " second ");
        }else{
            formattedDiff.append(seconds + " seconds ");
        }
    }


    return formattedDiff.toString();
}

它与StringBuilder一起将所有内容附加在一起。

答案 6 :(得分:1)

我尝试过这种方法..但不知道为什么我没有得到正确的结果

long diff = date1.getTime() - date2.getTime();
long seconds = diff / 1000;
long minutes = seconds / 60;
long hours = minutes / 60;
long days = hours / 24;

但这可行

long miliSeconds = date1.getTime() -date2.getTime();
long seconds = TimeUnit.MILLISECONDS.toSeconds(miliSeconds);
long minute = seconds/60;
long hour = minute/60;
long days = hour/24;

答案 7 :(得分:1)

如何使用 Instant

annotations:
    kubed.appscode.com/sync: "cert-manager-tls=dev" 

您甚至可以使用 instant1.toString() 保存您的 Instant 并使用 parse(string) 解析该字符串。

如果您需要支持 Android API 级别 < 26 只需添加 Java 8+ API desugaring support 到您的项目。

答案 8 :(得分:0)

使用这些功能

    public static int getDateDifference(
        int previousYear, int previousMonthOfYear, int previousDayOfMonth,
        int nextYear, int nextMonthOfYear, int nextDayOfMonth,
        int differenceToCount){
    // int differenceToCount = can be any of the following
    //  Calendar.MILLISECOND;
    //  Calendar.SECOND;
    //  Calendar.MINUTE;
    //  Calendar.HOUR;
    //  Calendar.DAY_OF_MONTH;
    //  Calendar.MONTH;
    //  Calendar.YEAR;
    //  Calendar.----

    Calendar previousDate = Calendar.getInstance();
    previousDate.set(Calendar.DAY_OF_MONTH, previousDayOfMonth);
    // month is zero indexed so month should be minus 1
    previousDate.set(Calendar.MONTH, previousMonthOfYear);
    previousDate.set(Calendar.YEAR, previousYear);

    Calendar nextDate = Calendar.getInstance();
    nextDate.set(Calendar.DAY_OF_MONTH, previousDayOfMonth);
    // month is zero indexed so month should be minus 1
    nextDate.set(Calendar.MONTH, previousMonthOfYear);
    nextDate.set(Calendar.YEAR, previousYear);

    return getDateDifference(previousDate,nextDate,differenceToCount);
}
public static int getDateDifference(Calendar previousDate,Calendar nextDate,int differenceToCount){
    // int differenceToCount = can be any of the following
    //  Calendar.MILLISECOND;
    //  Calendar.SECOND;
    //  Calendar.MINUTE;
    //  Calendar.HOUR;
    //  Calendar.DAY_OF_MONTH;
    //  Calendar.MONTH;
    //  Calendar.YEAR;
    //  Calendar.----

    //raise an exception if previous is greater than nextdate.
    if(previousDate.compareTo(nextDate)>0){
        throw new RuntimeException("Previous Date is later than Nextdate");
    }

    int difference=0;
    while(previousDate.compareTo(nextDate)<=0){
        difference++;
        previousDate.add(differenceToCount,1);
    }
    return difference;
}

答案 9 :(得分:0)

使用格鲁吉亚卡兰德

 public void dateDifferenceExample() {

        // Set the date for both of the calendar instance
        GregorianCalendar calDate = new GregorianCalendar(2012, 10, 02,5,23,43);
        GregorianCalendar cal2 = new GregorianCalendar(2015, 04, 02);

        // Get the represented date in milliseconds
        long millis1 = calDate.getTimeInMillis();
        long millis2 = cal2.getTimeInMillis();

        // Calculate difference in milliseconds
        long diff = millis2 - millis1;

        // Calculate difference in seconds
        long diffSeconds = diff / 1000;

        // Calculate difference in minutes
        long diffMinutes = diff / (60 * 1000);

        // Calculate difference in hours
        long diffHours = diff / (60 * 60 * 1000);

        // Calculate difference in days
        long diffDays = diff / (24 * 60 * 60 * 1000);
    Toast.makeText(getContext(), ""+diffSeconds, Toast.LENGTH_SHORT).show();


}

答案 10 :(得分:0)

用Kotlin编写: 如果您需要两个日期之间的差额,并且不关心日期本身(例如,如果您需要在应用中执行某些操作,这是基于其他操作时间(例如保存在共享首选项中的时间),那么很好)。 第一次保存:

val firstTime:Long= System.currentTimeMillis()

第二次保存:

val now:Long= System.currentTimeMillis()

计算两次之间的毫秒数:

val milisecondsSinceLastTime: Long =(now-lastScrollTime)

答案 11 :(得分:-1)

最短的答案对我有用。以毫秒为单位发送开始和结束日期。

public int GetDifference(long start,long end){
    Calendar cal = Calendar.getInstance();
    cal.setTimeInMillis(start);
    int hour = cal.get(Calendar.HOUR_OF_DAY);
    int min = cal.get(Calendar.MINUTE);
    long t=(23-hour)*3600000+(59-min)*60000;

    t=start+t;

    int diff=0;
    if(end>t){
        diff=(int)((end-t)/ TimeUnit.DAYS.toMillis(1))+1;
    }

    return  diff;
}