Over a million developers have joined DZone.

Notes on Java’s Date class

DZone's Guide to

Notes on Java’s Date class

· Java Zone ·
Free Resource

The CMS developers love. Open Source, API-first and Enterprise-grade. Try BloomReach CMS for free.

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());
    Date utc = c.getTime();
    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");
    String utc = utcFormat.format(date);
    String mst = mstFormat.format(date);
    assert !utc.equals(mst);  //should not throw AssertionError

From http://codeaweso.me/2010/09/notes-on-javas-date-class/

BloomReach CMS: the API-first CMS of the future. Open-source & enterprise-grade. - As a Java developer, you will feel at home using Maven builds and your favorite IDE (e.g. Eclipse or IntelliJ) and continuous integration server (e.g. Jenkins). Manage your Java objects using Spring Framework, write your templates in JSP or Freemarker. Try for free.


Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}