Notes on Java’s Date class
Notes on Java’s Date class
Join the DZone community and get the full member experience.
Join For FreeGet the Edge with a Professional Java IDE. 30-day free trial.
Every so often I get myself confused about Java’s often-obtuse handling of dates and timezones. So, for my future self’s benefit, here are some reminder notes…
Please leave a comment if you have corrections or additional tips! (And, preemptively, yes, some day I’ll give Joda Time a try.)
- Dates do not have timezones; they reflect UTC.
- Date.toString() returns a String representation based on the local machine’s default timezone. This makes people think that Dates have timezones.
- You cannot convert a Date from one timezone to another.
Calendar c = Calendar.getInstance(); c.setTime(new Date()); c.setTimeZone(TimeZone.getTimeZone("UTC")); Date utc = c.getTime(); c.setTimeZone(TimeZone.getTimeZone("America/Phoenix")); Date mst = c.getTime(); assert !utc.equals(mst); //throws AssertionError
- However, you can use DateFormat to affect the String representation of a Date, including the timezone.
Date date = new Date(); SimpleDateFormat utcFormat = new SimpleDateFormat("ddHHmm"); SimpleDateFormat mstFormat = new SimpleDateFormat("ddHHmm"); utcFormat.setTimeZone(TimeZone.getTimeZone("UTC")); mstFormat.setTimeZone(TimeZone.getTimeZone("America/Phoenix")); String utc = utcFormat.format(date); String mst = mstFormat.format(date); assert !utc.equals(mst); //should not throw AssertionError
Get the Java IDE that understands code & makes developing enjoyable. Level up your code with IntelliJ IDEA. Download the free trial.
Opinions expressed by DZone contributors are their own.
{{ parent.title || parent.header.title}}
{{ parent.tldr }}
{{ parent.linkDescription }}
{{ parent.urlSource.name }}