Explain Codes LogoExplain Codes Logo

Changing Java Date one hour back

java
java-8
date-time
time-zone
Alex KataevbyAlex Kataev·Feb 1, 2025
TLDR

Quick solution to subtract an hour from a Date involves using the Calendar class:

Date now = new Date(); // current date and time Calendar cal = Calendar.getInstance(); // create a Calendar instance cal.setTime(now); // Set Calendar time cal.add(Calendar.HOUR_OF_DAY, -1); // Subtract an hour Date oneHourBack = cal.getTime(); // One hour prior System.out.println(oneHourBack); // Print the result

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:

// Create LocalDateTime instances LocalDateTime now = LocalDateTime.now(); // Present time LocalDateTime oneHourBack = now.minusHours(1); // Rewinds one hour // Create ZonedDateTime instances ZonedDateTime zonedNow = ZonedDateTime.now(); // UTC isn't always fun, let's add some timezone spice ZonedDateTime zonedOneHourBack = zonedNow.minusHours(1); // The Earth just reversed its rotation by one hour

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:

Instant instantNow = Instant.now(); // Current timestamp — UTC Instant instantOneHourBack = instantNow.minus(1, ChronoUnit.HOURS); // Time machine in action

Interesting: Instant thinks in UTC/GMT. Time zones? What time zones?

Leveraging TimeUnit for clarity

Promote code readability when subtracting hours using TimeUnit:

long oneHourInMilliseconds = TimeUnit.HOURS.toMillis(1); // Converts 1 hour to milliseconds Date newDate = new Date(System.currentTimeMillis() - oneHourInMilliseconds); // Subtract an hour from current time

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:

Instant dateToInstant = new Date().toInstant(); // Convert Date to Instant Date instantToDate = Date.from(Instant.now()); // Convert Instant to Date

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:

org.joda.time.LocalDateTime jodaNow = org.joda.time.LocalDateTime.now(); org.joda.time.LocalDateTime jodaOneHourBack = jodaNow.minusHours(1);

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:

// Set query parameters with java.time classes PreparedStatement st = con.prepareStatement("SELECT * FROM events WHERE event_time > ?"); st.setObject(1, LocalDateTime.now()); // Who knew databases and times could be such good friends?

Time zone and DST: It's not a party without them

Remember time zones and DST while dealing with time-sensitive data:

ZonedDateTime zonedNow = ZonedDateTime.now(ZoneId.of("America/New_York")); // Current time in New York, USA ZonedDateTime zonedOneHourBack = zonedNow.minusHours(1); // New Yorkers just got an extra hour of sleep

Tip: The rarest of bugs occur due to time shifts. So, always test during DST changes.