开发者

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 开发者_StackOverflowhour 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)?


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"


 date1.getTime() - date2.getTime() 

This will return you the time in miliseconds between the 2 dates. Just convert that to what ever you want to show (e.g. hours minutes seconds)


On Android, use this: http://developer.android.com/reference/android/text/format/DateUtils.html#getRelativeTimeSpanString%28android.content.Context,%20long,%20boolean%29


Take a look at PrettyTime!

Also, everytime you want to do something date/time-related in Java, you should take a look at Joda Time. Do it now, you will thank me later.


Your need is very specific, and I don't know any lib that would solve the problem for you out of the box. However the problem is not very complex and a small function full of "ifs" should do the trick. Of course, a nice date library like Joda Time will help you keep your code clean. Who wants to use GregorianCalendar!?


Looks like you have a set of custom rules and the algorithm to choose a rule is based on the time in seconds between two timestamps. The easiest approach is to handle the rules in a series of if/else if statements:

 private String getTimeAsString(int seconds) {
   if (seconds < 60) {     // rule 1
      return String.format("%s seconds ago", seconds);
   } else if (seconds < 3600) {  // rule 2
      return String.format("%s minutes ago", seconds/60);
   } // ... and so on
 }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜