1

I want to find the time left till some day and time. I mean that if the target time is March 27th ( year 2017 ) at 10 oclock and today is March 10th 8 oclock so the time left is 17 days and 2 hours.

Is there some way using the date android API to calculate this time left?

morten.c
  • 3,414
  • 5
  • 40
  • 45
Yanshof
  • 9,659
  • 21
  • 95
  • 195

2 Answers2

4

You can do this by calling this method:

public static Map<TimeUnit,Long> computeDiff(Date date1, Date date2) {
    long diffInMillies = date2.getTime() - date1.getTime();
    List<TimeUnit> units = new ArrayList<TimeUnit>(EnumSet.allOf(TimeUnit.class));
    Collections.reverse(units);
    Map<TimeUnit,Long> result = new LinkedHashMap<TimeUnit,Long>();
    long milliesRest = diffInMillies;
    for ( TimeUnit unit : units ) {
        long diff = unit.convert(milliesRest,TimeUnit.MILLISECONDS);
        long diffInMilliesForUnit = unit.toMillis(diff);
        milliesRest = milliesRest - diffInMilliesForUnit;
        result.put(unit,diff);
    }
    return result;
}

It give you a map of timeUnit and their value like:

Map:{DAYS=1, HOURS=3, MINUTES=46, SECONDS=40, MILLISECONDS=0, MICROSECONDS=0, NANOSECONDS=0},

Then you can convert it to anything you want.

Mohammad Zarei
  • 1,773
  • 14
  • 33
0

Use

 long futureTimeMillis;
 long currentTimeMillis
 DateUtils.getRelativeTimeSpanString(futureTimeMillis, currentTimeMillis, DateUtils.MINUTE_IN_MILLIS);
ayz4sci
  • 2,220
  • 1
  • 16
  • 17