Changing Java Date one hour back
Quick solution to subtract an hour from a Date
involves using the Calendar
class:
Here, we use Calendar.HOUR_OF_DAY
and the add
method with -1
to roll back the hour.
Java 8 and newer: The modern way
java.time: LocalDateTime and ZonedDateTime classes
Java 8 gave us the new java.time
classes, providing easier and more readable date/time operations:
Fact: our ZonedDateTime
friend automatically takes care of time zone differences and the pesky Daylight Saving Time (DST).
Using an Instant: Short, sharp, and to the point
Instant
is useful when you need a specific timestamp:
Interesting: Instant
thinks in UTC/GMT. Time zones? What time zones?
Leveraging TimeUnit for clarity
Promote code readability when subtracting hours using TimeUnit
:
Hint: TimeUnit
ensures your code remains expressive and eliminates any magic numbers.
Options for both modern and ancient artifacts
Converting between java.util.Date and java.time
Here's a bridge between the old (pre Java 8) and the new:
Funny: It's like taking a black and white photo and recoloring it!
Joda-Time: The Java chronologist's favorite tool
Before the advent of java.time
classes, Joda-Time was the library that saved many developers from premature grey hair:
While java.time
has overtaken it, Joda-Time helps maintain sanity for those stuck with legacy projects.
Database readiness: JDBC driver compatibility
JDBC drivers released after version 4.2 fully support java.time
classes:
Time zone and DST: It's not a party without them
Remember time zones and DST while dealing with time-sensitive data:
Tip: The rarest of bugs occur due to time shifts. So, always test during DST changes.
Was this article helpful?