Получение разницы между двумя датами Android - PullRequest
6 голосов
/ 01 августа 2011

У меня есть дата публикации строки, например:

2011-03-27T09:39:01.607

и текущая дата.

Я хочу получить разницу между этими двумя датами в виде:

2 days ago 
1 minute ago etc..

в зависимости от даты публикации.

Использую этот код для преобразования даты публикации в миллисекунды:

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

текущую дату: long now = System.currentTimeMillis();

и для расчетаРазница:

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

Но возвращается как May 1 , 1970 или что-то еще.

Как получить разницу между датой публикации и текущей датой.

Ответы [ 6 ]

21 голосов
/ 01 августа 2011

Вы можете использовать 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();
}
7 голосов
/ 01 августа 2011

Конвертируйте обе даты в календарь и сделайте время 0 (

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

).
Тогда используйте это удовольствие:

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));
    }
4 голосов
/ 04 декабря 2012

Попробуйте следующий метод, который я использовал в одном из моих приложений:

/**
 * 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();
}
2 голосов
/ 30 мая 2013

Простой способ реализовать это:

  1. импортировать библиотеку joda в ваш проект.

  2. сохранять текущую и будущую дату в переменной, напримерthis

    //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. Выбранные единицы из настроек будут иметь любые единицы, которые вы пожелаете.

1 голос
/ 05 марта 2015

Вы можете найти разницу между двумя датами , не используя библиотеку

Вам просто нужно выяснить разницу между датами:

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

этим вы получите разницу в миллисекундах .. Теперь вы можете отформатировать это в соответствии со своими потребностями, т.е. в формате часов назад, месяцев назад или лет назад , просто используя условия if

См. Полный пример ЗДЕСЬ ..

Надеюсь, это поможет ..!

0 голосов
/ 01 августа 2011

Причина, по которой вы получаете 1970, состоит в том, что это дата эпохи в миллисекундах. Чтобы получить реальную разницу, используйте ниже.

Использование JodaTime

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...