Explain Codes LogoExplain Codes Logo

How to set time zone of a java.util.Date?

java
time-zone
date-parsing
joda-time
Nikita BarsukovbyNikita BarsukovΒ·Aug 10, 2024
⚑TLDR
import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; // Create a formatter for displaying Date in a specific time zone. // Like dressing up the time in a New York Yankees jersey. πŸ˜‰ SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); sdf.setTimeZone(TimeZone.getTimeZone("America/New_York")); Date now = new Date(); // Current date/time in UTC. Naked as the day it was born! String nyTime = sdf.format(now); // Dressing the time in New York flavor. System.out.println(nyTime); // Time struts its New York style.

Remember: java.util.Date cares as much about the time zone as a honey badger does; we're altering the display to reflect a time zone, not the underlying date.

Parsing dates: Only if it has the sauce

When date strings are involved, you'll need a good parser. It's like explaining a foreign movie to a friend:

String input = "2023-04-05 10:30:00"; SimpleDateFormat parser = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // Tell the parser we're watching a British movie. parser.setTimeZone(TimeZone.getTimeZone("Europe/London")); try { // Let the parser explain the British twist in time. πŸŽ₯⏳ Date parsedDate = parser.parse(input); } catch (ParseException e) { // Spoiler alert: The British twist could be too much! e.printStackTrace(); }

Displaying dates in different time zones: It's showtime!

Now comes the presentation. Paint your date string in any timezone you want:

SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // We're going Japanese now. πŸ‡―πŸ‡΅β²οΈ formatter.setTimeZone(TimeZone.getTimeZone("Asia/Tokyo")); // The British date takes a Samurai stance! String tokyoTime = formatter.format(parsedDate);

Modern date API: Time travel made easy

Wanna feel like Doctor Who? Use the modern java.time package to manipulate dates:

import java.time.*; // Let's start from London... LocalDateTime ldt = LocalDateTime.parse(input, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); ZonedDateTime zdt = ldt.atZone(ZoneId.of("Europe/London")); // ...And take our time to Tokyo! πŸŒ€β²οΈπŸŒ ZonedDateTime converted = zdt.withZoneSameInstant(ZoneId.of("Asia/Tokyo"));

Potholes on the way

System time zone: The invisible puppeteer

Your system default time zone can play puppeteer and mess with your date parsing. If you mess with it using TimeZone.setDefault(), even Chuck Norris gets a day off!

Naming time zones: Say my name, say my name

In the world of time zones, "EST" could be a shy girl named Eastern Standard Time or Australian Eastern Standard Time, the twin nobody knew about. Always use full time zone names to avoid confusion.

Daylight Saving: Time's mood swings

Time has mood swings called daylight saving changes. It can spring forward or fall back. Keep this in mind while converting dates.

Check before you parse

Like checking your parachute before a jump, ensure input date format matches the expected format.

Alternatives and methods: Choose your weapon

Joda-Time: The Obi-Wan before java.time

Before java.time was the chosen one, we had Joda-Time:

import org.joda.time.*; DateTime dt = new DateTime(input, DateTimeZone.forID("Europe/London")); DateTime convertedDt = dt.withZone(DateTimeZone.forID("Asia/Tokyo"));

Setting JVM-wide time zones: With great power...

...comes a great responsibility. Handle -Duser.timezone="TimeZoneID" carefully, if you must.

Manual timezone conversions: Down the rabbit hole

You can convert time zones manually. Like counting stars in the sky, it's hectic and error-prone. Remember, daylight saving is a tricky beast.