Search code examples
javaandroidtimetimestampdate-arithmetic

java calculate time between two timestamps


I need to calculate the time passed between two dates.

The catch here is that I need to show it as YouTube does with its video comments timestamps. That is, to show it by just the largest measure.

For example,

  • if the time is 50 seconds ago it should say 50 seconds ago.
  • if the time is more than one minute it should say one minute ago/ten minutes ago etc..
  • if the time difference is 1 hour 30 mins it should show: an hour ago.
  • if the time is one and a half week than it should say one week ago.
  • if the time is more than a month it should say one month ago/two months ago etc...
  • and so on and so on..

So what is the best way to handle this? Should I make a method with case or if statements that would return something like this? Or is there a better approach (maybe a library which already does something like it)?


Solution

  • Use DateUtils.getRelativeTimeSpanString(long time, long now, long minResolution). time is the start time, and now is the end time (in milliseconds). To report "seconds ago," set minResolution to zero.

    Example:

    String result = DateUtils.getRelativeTimeSpanString(1306767830, 1306767835, 0);
    // result = "5 seconds ago"