How to set time zone of a java.util.Date?
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:
Displaying dates in different time zones: It's showtime!
Now comes the presentation. Paint your date string in any timezone you want:
Modern date API: Time travel made easy
Wanna feel like Doctor Who? Use the modern java.time
package to manipulate dates:
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:
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.
Was this article helpful?