java 获取两个日期之间的差异 Android

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6897027/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 17:48:59  来源:igfitidea点击:

Getting difference between two dates Android

javaandroiddate

提问by Udaykiran

Am having string posting date like :

我的字符串发布日期如下:

2011-03-27T09:39:01.607

and There is current date .

并且有当前日期。

I want to get difference between these two dates in the form of :

我想以以下形式获得这两个日期之间的差异:

2 days ago 
1 minute ago etc..

depending posting date.

取决于发布日期。

Am using this code to convert posting date to milliseconds:

我正在使用此代码将发布日期转换为毫秒:

public long Date_to_MilliSeconds(int day, int month, int year, int hour, int minute) {
    Calendar c = Calendar.getInstance();
    c.set(year, month, day, hour, minute, 00);
    return c.getTimeInMillis();
}

this current date: long now = System.currentTimeMillis();

当前日期: long now = System.currentTimeMillis();

and to calculate difference:

并计算差异:

String difference = (String) DateUtils.getRelativeTimeSpanString(time,now, 0);

But it returning like May 1 , 1970or something ..

但它返回之类的May 1 , 1970..

How to get the difference between posting date and current date.

如何获取发布日期和当前日期之间的差异。

采纳答案by PravinCG

The reason you get 1970 is because it is the epoch date in milli seconds. To get the actual difference use the below.

你得到 1970 的原因是因为它是以毫秒为单位的纪元日期。要获得实际差异,请使用以下内容。

Use JodaTime

使用JodaTime

回答by Lawrence Barsanti

You can use getRelativeTimeSpanString(). It returns a string like "1 minute ago". Here is a real simple example that tells how long the application has been running.

您可以使用getRelativeTimeSpanString()。它返回一个字符串,如“1 分钟前”。这是一个真正简单的示例,它说明应用程序运行了多长时间。

private long mStartTime;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    mStartTime = System.currentTimeMillis();
}

public void handleHowLongClick(View v) {
    CharSequence cs = DateUtils.getRelativeTimeSpanString(mStartTime);
    Toast.makeText(this, cs, Toast.LENGTH_LONG).show();
}

回答by ShineDown

Convert both dates into calender and make time 0(

将两个日期转换为日历并使时间为 0(

today.set(Calendar.HOUR_OF_DAY, 0);
    today.set(Calendar.MINUTE, 0);
    today.set(Calendar.SECOND, 0);

).
Then use this fun :

)。
然后使用这个乐趣:

public final static long SECOND_MILLIS = 1000;
public final static long MINUTE_MILLIS = SECOND_MILLIS*60;
public final static long HOUR_MILLIS = MINUTE_MILLIS*60;
public final static long DAY_MILLIS = HOUR_MILLIS*24;

 public static int daysDiff( Date earlierDate, Date laterDate )
    {
        if( earlierDate == null || laterDate == null ) return 0;
        return (int)((laterDate.getTime()/DAY_MILLIS) - (earlierDate.getTime()/DAY_MILLIS));
    }

回答by Munim Dibosh

Try the following method that I used in one of my applications:

尝试我在我的一个应用程序中使用的以下方法:

/**
 * Returns difference between time and current time as string like:
 * "23 mins ago" relative to current time.
 * @param time - The time to compare with current time in yyyy-MM-dd HH:mm:ss format
 * @param currentTime - Present time in yyyy-MM-dd HH:mm:ss format
 * @return String - The time difference as relative text(e.g. 23 mins ago)
 * @throws ParseException
 */
private String getTimeDiff(String time, String currentTime) throws ParseException
{
    DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date currentDate = (Date)formatter.parse(currentTime);
    Date oldDate = (Date)formatter.parse(time);
    long oldMillis = oldDate.getTime();
    long currentMillis = currentDate.getTime();
    return DateUtils.getRelativeTimeSpanString(oldMillis, currentMillis, 0).toString();
}

回答by Swapnil

Simple way to implement this:

实现这一点的简单方法:

  1. import joda library in your project.

  2. store your current date and future date in variable like this

    //here currenDate and futureDate are of calendar type.
    LocalDateTime currentDateTime = LocalDateTime.fromCalendarFields(currentDate);
    LocalDateTime futureDateTime = LocalDateTime.fromCalendarFields(futureDate);
    
  3. Now what you have to do is calculate difference between the two dates and save the difference,this difference will be used to subtract from next field.

    for example: we have to display years,months,weeks...and so forth. after calculating years between the two dates we will minus the years amount from the months and similarly for the next fields...Hierarchy of the date time is as follows...

    years-months-weeks-days-hours-minutes-seconds

    now the snippet

    /**
     * 
     * @param context which activity its calling
     * @param currentDateTime current time 
     * @param futureDateTime future time from which we have to calculate difference
     * @param selectedUnitsFromSettings which units we have to find difference such as years,weeks....etc
     *  which will be stored in list...
     * @return
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static HashMap dateBasedOnUnitCalculator(
            Context ctx, LocalDateTime currentDateTime,
            LocalDateTime futureDateTime, List<String> selectedUnitsFromSettings) {
    
        //to store the dates
        Date currentTime = currentDateTime.toDateTime().toDate();
        Date futureTime = futureDateTime.toDateTime().toDate();
    
        //to store the units
        String currentUnit = "";
        String prevUnit = "";
    
        //to store the value which you want to remove
        int prevValue = 0;
    
        //to store the calculated values in hashmap
        HashMap units = new HashMap();
    
        for(int i = 0; i < selectedUnitsFromSettings.size(); i++){
            //to store the current unit for calculation of future date
            currentUnit = selectedUnitsFromSettings.get(i);
            //to remove higher unit from new future date we will use prevUnit
            if(i > 0){
                prevUnit = selectedUnitsFromSettings.get(i-1);
                futureTime = getDateForPreviousUnit(futureTime,prevUnit,prevValue);
            }
    
            //now calculate the difference
                if(currentUnit.equals("Year")){
                Years q = Years.yearsBetween(new DateTime(currentTime.getTime()), new DateTime(futureTime.getTime()));
                int years = q.getYears();
                prevValue = years;
                units.put("Year", prevValue);
            }else if(currentUnit.equals("Month")){
                Months w =  Months.monthsBetween(new DateTime(currentTime.getTime()), new DateTime(futureTime.getTime()));
                int months = w.getMonths();
                prevValue = months;
                units.put("Month", prevValue);
            }else if(currentUnit.equals("Week")){
                Weeks e = Weeks.weeksBetween(new DateTime(currentTime.getTime()), new DateTime(futureTime.getTime()));
                int weeks = e.getWeeks();
                prevValue = weeks;
                units.put("Week", prevValue);
            }else if(currentUnit.equals("Day")){
                Days r = Days.daysBetween(new DateTime(currentTime.getTime()), new DateTime(futureTime.getTime()));
                int days = r.getDays();
                prevValue = days;
                units.put("Day", prevValue);
            }else if(currentUnit.equals("Hour")){
                Hours a = Hours.hoursBetween(new DateTime(currentTime.getTime()), new DateTime(futureTime.getTime()));
                int hours = a.getHours();
                prevValue = hours;
                units.put("Hour", prevValue);
            }else if(currentUnit.equals("Minute")){
                Minutes s = Minutes.minutesBetween(new DateTime(currentTime.getTime()), new DateTime(futureTime.getTime()));
                int minutes = s.getMinutes();
                prevValue = minutes;
                units.put("Minute", prevValue);
            }else if(currentUnit.equals("Second")){
                Seconds d = Seconds.secondsBetween(new DateTime(currentTime.getTime()), new DateTime(futureTime.getTime()));
                int seconds = d.getSeconds();
                prevValue = seconds;
                units.put("Second", prevValue);
            }
    
        }
    
        return units;
    }
    

    to calculate future time for previous unit

    /**
     * 
     * @param futureTime the future date which will be modified
     * @param prevString which unit value to be reduced
     * @param prevValue how much to reduce from the current unit
     * @return
     */
    private static Date getDateForPreviousUnit(Date futureTime,
            String prevString, int prevValue) {
    
        Date calculatedDate = futureTime;
        Constants.showLog(TAG, "prev string is "+prevString);
    
        if(prevString.equals("Year")){
            calculatedDate = new DateTime(futureTime).minusYears(prevValue).toDate();
        }else if(prevString.equals("Month")){
            calculatedDate = new DateTime(futureTime).minusMonths(prevValue).toDate();
        }else if(prevString.equals("Week")){
            calculatedDate = new DateTime(futureTime).minusWeeks(prevValue).toDate();
        }else if(prevString.equals("Day")){
            calculatedDate = new DateTime(futureTime).minusDays(prevValue).toDate();
        }else if(prevString.equals("Hour")){
            calculatedDate = new DateTime(futureTime).minusHours(prevValue).toDate();
        }else if(prevString.equals("Minute")){
            calculatedDate = new DateTime(futureTime).minusMinutes(prevValue).toDate();
        }else if(prevString.equals("Second")){
            calculatedDate = new DateTime(futureTime).minusSeconds(prevValue).toDate();
        }
    
        return calculatedDate;
    }
    
  4. now to call from any activity use this

    HashTable hashTable = dateBasedOnUnitCalculator(this, currentDateTime, futureDateTime, selectedUnitsFromSettings);
    
                   //to display the values from hashtable
        showLog(TAG,
                " year "+hashTable.get("Year") +
                " month "+hashTable.get("Month") +
                " week "+hashTable.get("Week") +
                " day "+hashTable.get("Day") + 
                " hours "+hashTable.get("Hour") + 
                " min " +hashTable.get("Minute") +
                " sec " +hashTable.get("Second") + 
                " ");
    
  5. selectedunitsfromsettings will have any units you desire.

  1. 在您的项目中导入 joda 库。

  2. 将您的当前日期和未来日期存储在这样的变量中

    //here currenDate and futureDate are of calendar type.
    LocalDateTime currentDateTime = LocalDateTime.fromCalendarFields(currentDate);
    LocalDateTime futureDateTime = LocalDateTime.fromCalendarFields(futureDate);
    
  3. 现在您要做的是计算两个日期之间的差异并保存差异,该差异将用于从下一个字段中减去。

    例如:我们必须显示年、月、周……等等。在计算两个日期之间的年数后,我们将从月份中减去年数,对于下一个字段也是如此......日期时间的层次结构如下......

    年-月-周-天-小时-分-秒

    现在是片段

    /**
     * 
     * @param context which activity its calling
     * @param currentDateTime current time 
     * @param futureDateTime future time from which we have to calculate difference
     * @param selectedUnitsFromSettings which units we have to find difference such as years,weeks....etc
     *  which will be stored in list...
     * @return
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static HashMap dateBasedOnUnitCalculator(
            Context ctx, LocalDateTime currentDateTime,
            LocalDateTime futureDateTime, List<String> selectedUnitsFromSettings) {
    
        //to store the dates
        Date currentTime = currentDateTime.toDateTime().toDate();
        Date futureTime = futureDateTime.toDateTime().toDate();
    
        //to store the units
        String currentUnit = "";
        String prevUnit = "";
    
        //to store the value which you want to remove
        int prevValue = 0;
    
        //to store the calculated values in hashmap
        HashMap units = new HashMap();
    
        for(int i = 0; i < selectedUnitsFromSettings.size(); i++){
            //to store the current unit for calculation of future date
            currentUnit = selectedUnitsFromSettings.get(i);
            //to remove higher unit from new future date we will use prevUnit
            if(i > 0){
                prevUnit = selectedUnitsFromSettings.get(i-1);
                futureTime = getDateForPreviousUnit(futureTime,prevUnit,prevValue);
            }
    
            //now calculate the difference
                if(currentUnit.equals("Year")){
                Years q = Years.yearsBetween(new DateTime(currentTime.getTime()), new DateTime(futureTime.getTime()));
                int years = q.getYears();
                prevValue = years;
                units.put("Year", prevValue);
            }else if(currentUnit.equals("Month")){
                Months w =  Months.monthsBetween(new DateTime(currentTime.getTime()), new DateTime(futureTime.getTime()));
                int months = w.getMonths();
                prevValue = months;
                units.put("Month", prevValue);
            }else if(currentUnit.equals("Week")){
                Weeks e = Weeks.weeksBetween(new DateTime(currentTime.getTime()), new DateTime(futureTime.getTime()));
                int weeks = e.getWeeks();
                prevValue = weeks;
                units.put("Week", prevValue);
            }else if(currentUnit.equals("Day")){
                Days r = Days.daysBetween(new DateTime(currentTime.getTime()), new DateTime(futureTime.getTime()));
                int days = r.getDays();
                prevValue = days;
                units.put("Day", prevValue);
            }else if(currentUnit.equals("Hour")){
                Hours a = Hours.hoursBetween(new DateTime(currentTime.getTime()), new DateTime(futureTime.getTime()));
                int hours = a.getHours();
                prevValue = hours;
                units.put("Hour", prevValue);
            }else if(currentUnit.equals("Minute")){
                Minutes s = Minutes.minutesBetween(new DateTime(currentTime.getTime()), new DateTime(futureTime.getTime()));
                int minutes = s.getMinutes();
                prevValue = minutes;
                units.put("Minute", prevValue);
            }else if(currentUnit.equals("Second")){
                Seconds d = Seconds.secondsBetween(new DateTime(currentTime.getTime()), new DateTime(futureTime.getTime()));
                int seconds = d.getSeconds();
                prevValue = seconds;
                units.put("Second", prevValue);
            }
    
        }
    
        return units;
    }
    

    计算上一单元的未来时间

    /**
     * 
     * @param futureTime the future date which will be modified
     * @param prevString which unit value to be reduced
     * @param prevValue how much to reduce from the current unit
     * @return
     */
    private static Date getDateForPreviousUnit(Date futureTime,
            String prevString, int prevValue) {
    
        Date calculatedDate = futureTime;
        Constants.showLog(TAG, "prev string is "+prevString);
    
        if(prevString.equals("Year")){
            calculatedDate = new DateTime(futureTime).minusYears(prevValue).toDate();
        }else if(prevString.equals("Month")){
            calculatedDate = new DateTime(futureTime).minusMonths(prevValue).toDate();
        }else if(prevString.equals("Week")){
            calculatedDate = new DateTime(futureTime).minusWeeks(prevValue).toDate();
        }else if(prevString.equals("Day")){
            calculatedDate = new DateTime(futureTime).minusDays(prevValue).toDate();
        }else if(prevString.equals("Hour")){
            calculatedDate = new DateTime(futureTime).minusHours(prevValue).toDate();
        }else if(prevString.equals("Minute")){
            calculatedDate = new DateTime(futureTime).minusMinutes(prevValue).toDate();
        }else if(prevString.equals("Second")){
            calculatedDate = new DateTime(futureTime).minusSeconds(prevValue).toDate();
        }
    
        return calculatedDate;
    }
    
  4. 现在从任何活动调用使用这个

    HashTable hashTable = dateBasedOnUnitCalculator(this, currentDateTime, futureDateTime, selectedUnitsFromSettings);
    
                   //to display the values from hashtable
        showLog(TAG,
                " year "+hashTable.get("Year") +
                " month "+hashTable.get("Month") +
                " week "+hashTable.get("Week") +
                " day "+hashTable.get("Day") + 
                " hours "+hashTable.get("Hour") + 
                " min " +hashTable.get("Minute") +
                " sec " +hashTable.get("Second") + 
                " ");
    
  5. selectedunitsfromsettings 将具有您想要的任何单位。

回答by Gagan Deep

You can find difference between two dates without using any library

您可以在不使用任何库的情况下找到两个日期之间的差异

You just need to find out difference between dates like this :

您只需要找出这样的日期之间的差异:

    long diff = currentdate.getTime() - temp_date.getTime();
                    //current date            //other date

by this you will get difference in milliseconds .. Now you can format this according to your need i.e in hours ago or months ago or years agoformat,just by using if conditions

通过这个你会得到毫秒的差异..现在你可以根据你的需要格式化它,即几小时前、几个月前或几年前的格式,只需使用 if 条件

See complete example HERE..

请参阅此处的完整示例..

Hope it helps..!

希望能帮助到你..!