fork(7) download
  1.  
  2. import java.util.concurrent.TimeUnit;
  3. import java.util.EnumSet;
  4. import java.util.Collections;
  5. import java.util.ArrayList;
  6. import java.util.List;
  7. import java.util.Map;
  8. import java.util.LinkedHashMap;
  9. import java.util.Date;
  10.  
  11. public class Main {
  12.  
  13. public static void main(String []args) {
  14. Map<TimeUnit,Long> result = computeDiff(
  15. new Date(System.currentTimeMillis()-100000000),
  16. new Date()
  17. );
  18. System.out.println(result);
  19. }
  20.  
  21. public static Map<TimeUnit,Long> computeDiff(Date date1, Date date2) {
  22. long diffInMillies = date2.getTime() - date1.getTime();
  23. List<TimeUnit> units = new ArrayList<TimeUnit>(EnumSet.allOf(TimeUnit.class));
  24. Collections.reverse(units);
  25.  
  26. Map<TimeUnit,Long> result = new LinkedHashMap<TimeUnit,Long>();
  27. long milliesRest = diffInMillies;
  28. for ( TimeUnit unit : units ) {
  29. long diff = unit.convert(milliesRest,TimeUnit.MILLISECONDS);
  30. long diffInMilliesForUnit = unit.toMillis(diff);
  31. milliesRest = milliesRest - diffInMilliesForUnit;
  32. result.put(unit,diff);
  33. }
  34. return result;
  35. }
  36.  
  37. }
  38.  
Success #stdin #stdout 0.08s 380160KB
stdin
Standard input is empty
stdout
{DAYS=1, HOURS=3, MINUTES=46, SECONDS=40, MILLISECONDS=0, MICROSECONDS=0, NANOSECONDS=0}