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

时间:2021-08-15 21:27:09

I saw all the post in here and still I can't figure how do get difference between two android dates.

我在这里看到了所有的帖子,但我仍然无法想象两个android日期之间如何区别。

This is what I do:

这就是我做的:

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

and I get: the date is Jan. 1, 1970 and the time is always bigger in two hours...I'm from Israel so the two hours is timeOffset.

我明白了:日期是1970年1月1日,时间总是在两个小时内变大......我来自以色列所以两个小时就是时间。

How can I get normal difference???

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

6 个解决方案

#1


58  

You're close to the right answer, you are getting the difference in milliseconds between those two dates, but when you attempt to construct a date out of that difference, it is assuming you want to create a new Date object with that difference value as its epoch time. If you're looking for a time in hours, then you would simply need to do some basic arithmetic on that diff to get the different time parts:

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

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

All of this math will simply do integer arithmetic, so it will truncate any decimal points

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

#2


11  

    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);

#3


10  

Some addition: Here I convert string to date then I compare the current time.

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

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();
    }

#4


1  

Use java.time.Duration:

使用java.time.Duration:

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

This will print something like

这将打印出类似的东西

PT109H27M21S

This means a period of time of 109 hours 27 minutes 21 seconds. If you want someting more human-readable — I’ll give the 9 version first, it’s simplest:

这意味着一段时间为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);

Now we get

现在我们得到了

4 days 13 hours 27 minutes 21 seconds

The Duration class is part of java.time the modern Java date and time API. This is bundled on newer Android devices. On older devices, get ThreeTenABP and add it to your project, and make sure to import org.threeten.bp.Duration and other date-time classes you may need from the same package.

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

Assuming you still haven’t got the Java 9 version, you may subtract the larger units in turn to get the smaller ones:

假设您还没有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();

Then you can format the four variables as above.

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

What did you do wrong?

A Date represents a point in time. It was never meant for representing an amount of time, a duration, and it isn’t suited for it. Trying to make that work would at best lead to confusing and hard-to-maintain code. You don’t want that, so please don’t.

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

Links

#5


0  

Use these functions

使用这些功能

    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;
}

#6


-1  

shortest answer that works for me. send start and end date in millisecond.

最适合我的答案。以毫秒为单位发送开始和结束日期。

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;
}

#1


58  

You're close to the right answer, you are getting the difference in milliseconds between those two dates, but when you attempt to construct a date out of that difference, it is assuming you want to create a new Date object with that difference value as its epoch time. If you're looking for a time in hours, then you would simply need to do some basic arithmetic on that diff to get the different time parts:

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

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

All of this math will simply do integer arithmetic, so it will truncate any decimal points

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

#2


11  

    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);

#3


10  

Some addition: Here I convert string to date then I compare the current time.

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

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();
    }

#4


1  

Use java.time.Duration:

使用java.time.Duration:

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

This will print something like

这将打印出类似的东西

PT109H27M21S

This means a period of time of 109 hours 27 minutes 21 seconds. If you want someting more human-readable — I’ll give the 9 version first, it’s simplest:

这意味着一段时间为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);

Now we get

现在我们得到了

4 days 13 hours 27 minutes 21 seconds

The Duration class is part of java.time the modern Java date and time API. This is bundled on newer Android devices. On older devices, get ThreeTenABP and add it to your project, and make sure to import org.threeten.bp.Duration and other date-time classes you may need from the same package.

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

Assuming you still haven’t got the Java 9 version, you may subtract the larger units in turn to get the smaller ones:

假设您还没有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();

Then you can format the four variables as above.

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

What did you do wrong?

A Date represents a point in time. It was never meant for representing an amount of time, a duration, and it isn’t suited for it. Trying to make that work would at best lead to confusing and hard-to-maintain code. You don’t want that, so please don’t.

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

Links

#5


0  

Use these functions

使用这些功能

    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;
}

#6


-1  

shortest answer that works for me. send start and end date in millisecond.

最适合我的答案。以毫秒为单位发送开始和结束日期。

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;
}