How to calculate "time ago" in Java?
The Java 8's java.time
API can be used to calculate "time ago" between two LocalDateTime
instances:
This snippet returns a well-formatted time ago string like "2 days ago" or "10 minutes ago".
Grammar rules: handling singular and plural forms
When showing time units, consider grammar rules. Specifically, look at singular and plural forms. Here is an improved way to output the correct suffix:
Repeat this for hours, minutes, and seconds. Because grammar matters, even in code.
Localization with PrettyTime and Android DateUtils
If your application needs to be multilingual, the PrettyTime library could come in handy, generating "time ago" values in various languages:
For Android developers, the built-in DateUtils class simplifies the process by providing a similar method: getRelativeTimeSpanString
.
Forming the "time ago" string
Building your own solution? Use a StringBuilder
to construct your "time ago" string more efficiently:
Convert time units accurately
For detailed time measurements, you can use TimeUnit
conversions:
These conversions ensure precise calculations for any time unit.
Robustness through error handling
Don't forget to cater edge cases, like 0 seconds or future dates. Safeguard your code with try-catch
blocks:
Not only days and hours
Include more detail with millisToLongDHMS
(a user-defined method) to provide detailed time intervals:
Reverse time calculation
A bonus would be providing a mechanism to convert back from a "time ago" string into milliseconds. It's like a time machine, but for your strings.
Finishing touch: Cleanup and formatting
Lastly, clean up your generated "time ago" string to remove any extra spaces or trailing characters:
Was this article helpful?