Compare current date-time [timestamp] with date-time chosen from a calendar dialog and display in user understandable way [closed]

StackOverflow https://stackoverflow.com/questions/23555611

  •  18-07-2023
  •  | 
  •  

Pergunta

I would like to display a set of user understandable date-time formats when user selects a date-time from a calendar dialog.

For ex:

  1. I don't choose a date a default current timestamp is formatted and displayed. In place of a date time that says "May 09th, 2014 07:40 AM" I want the textview to display "Now".
  2. If I select the time from the calendar dialog as "08:00 AM" (wrt to 07:00 AM current time), I should display as "in another 1 hour".
  3. And anything more than a day would say "Date - Time" (Existing format).
Foi útil?

Solução

I implemented the same thing recently by using Joda-Time.

By using this you can get the Time difference in different formats. sample code

Calendar cal = Calendar.getInstance();
cal.clear();
cal.set(Calendar.YEAR, 2014);
cal.set(Calendar.MONTH, Calendar.MAY);
cal.set(Calendar.DATE, 09);
cal.set(Calendar.HOUR_OF_DAY, 9);
Date startDate = cal.getTime();

//Use JodaTime to calculate difference
Period period =  getTimePassedSince(startDate);

//Extract values and display
long days= Math.abs(period.getDays()));
long hours= Math.abs(period.getHours()));
long minitues =Math.abs(period.getMinutes()));
long secnds =Math.abs(period.getSeconds()));

...
public static Period getTimePassedSince(Date initialTimestamp){
        DateTime initDT = new DateTime(initialTimestamp.getTime());
        DateTime now = new DateTime();
        Period p = new Period(initDT, now, PeriodType.dayTime()).normalizedStandard( PeriodType.dayTime());
        return p;
    }
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top