Chasing some subtle, annoying bugs in a block of code.
This code is given an instance of Calendar which was created at the start of some event. We need to figure out if this event is an hour old.
I know of several ways to do this:
- using JodaTime and calculating a Duration
- comparing the given Calendar to a new Calendar created for one hour ago
- comparing the given Calendar.getTime to a Date created for one hour ago
Each of these methods has its own quirks and seems to have code smells. Is there a simple, concise way to express “happened between now and one hour ago” in Java?
When I unit test this I would check:
- 45 minutes ago (true)
- 61 minutes ago (false)
- 0 minutes ago (true)
- -1 minutes ago (error or true?)
You can create a new Calendar instance (with current date/time) and compare it with the given one: