Java Glossary : calendar

CMP home Java glossary home Menu no menu Last updated 2004-06-28 by Roedy Green ©1996-2004 Canadian Mind Products

Java definitions: 0-9 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

You are here : home : Java Glossary : C words : calendar.

Calendar
Note the spelling. Java programmers rarely spell it correctly. This essay looks a little different from my usual style. That is because was published in 2001 Volume 6 issue 6 of Java Developer's Journal.

For newbies, dealing with dates and times are the probably the most confusing aspect of Java. There are three reasons for this:

  1. The date and time classes are the most poorly designed of all the Sun class libraries.
  2. The standard class libraries force you to deal with timezone and time of day, even when they are irrelevant to your problem.
  3. The vocabulary used in the various date classes is inconsistent.

Vocabulary

day of month
The day of the month 1..31. Sometimes called the date.
day of week
Day of the week for a given date, e.g. Sunday = 1, ... Saturday = 7.
DST offset
Daylight Saving Time offset. The number of milliseconds correction to account for daylight saving time, 0 if daylight saving time is not in effect for the timestamp specified. If a one-hour daylight saving is in effect, the offset will be 3600000. You add the DST offset and the zone offset to UTC to get local time.
ISO day of week
Day of the week 1 to 7 for this date according to the ISO standard IS-8601. Monday = 1 ... Sunday = 7.
ISO week number
Week number 1 to 53 of the year this date falls in, according to the rules of ISO standard IS-8601 section 5.5. A week that lies partly in one year and partly in another is assigned a number in the year in which most of its days lie. This means that week 1 of any year is the week that contains 4 January, or equivalently week 1 of any year is the week that contains the first Thursday in January. Most years have 52 weeks, but years that start on a Thursday and leap years that start on a Wednesday have 53 weeks. January 1 may well be in week 53 of the previous year!
Julian Date
I know of eight different definitions.
month of year
January to December. Note that in GregorianCalendar, January is month 0. In contrast, in DateFormat, January is month 1.
timestamp
An instant in cosmic time, expressed in milliseconds since January 1 1970 0:00 in UTC. It can be a positive or negative 64-bit long number. These are sometimes called Dates and sometimes Times.
offset
How many milliseconds difference local time is from UTC. If you live is North America this will be a negative number. It is the sum of the zone offset and the dst offset. You add the DST offset and the zone offset to UTC to get local time.
UTC
For all practical purposes it is just standard time at Greenwich England. The people in Greenwich use Daylight saving time, so the term GMT or Greenwich time would be ambiguous.
week of year
There are many possible definitions. The default GregorianCalendar definition depends on whether you consider Sunday or Monday as the first day of the week setFirstDayOfWeek, (the default is locale specific) and how many days you insist must be present in the first week of the year setMinimalDaysInFirstWeek, (default 1). The first week of the year is week 1. January 1 may sometimes be considered week 53 of the previous year.
zone offset
How many milliseconds difference local time is from UTC if you ignore any daylight saving time correction. If you live is North America this will be a negative number. You add the DST offset and the zone offset to UTC to get local time.

The Cast

You need to use quite a few different classes to solve even a simple problem involving dates. Examine the .
class Purpose
com.mindprod.business.BigDate A simpler date class for pure date calculations when you don't want the complication of TimeZones and times. Not part of Sun's libraries. You can download it from http://mindprod.com/products.html#BIGDATE
java.text.DateFormat Used to convert a date to or from a String. Contains an associated TimeZone.
java.text.SimpleDateFormat Used to convert a date to or from a String when you want precise control over the format. Contains an associated TimeZone.
java.util.Calendar Abstract class that is the mother of all Calendars such as GregorianCalendar. It owns the dozens of magic date constants such as Calendar.JANUARY = 0; Calendar.SUNDAY = 1; and Calendar.YEAR = 1.
java.util.Date Sun's first attempt at a Date class. I refer to it as the lemon of Java. It is now almost completely deprecated. It now just basically just a wrapper around a UTC date/timestamp long milliseconds since 1970. Unfortunately, it is still not completely gone.
java.util.GregorianCalendar Used to do date calculations. Each GregorianCalendar contains a UTC timestamp, and a TimeZone.
java.util.TimeZone Contains the name of a timezone and how many hours difference from UTC that timezone is. It also contains the rules for when daylight savings begins and ends. Timezones are named after cities. They are not the usual names.

Displaying A Date

This program will convert a date to a String for display, using the default date format. That format depends on what the user has configured as his preferred date format in the OS.

import java.text.DateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;

/**
 * display inauguration day as a String
 */
public class Inauguration1
   {
   static public void main (String [] args)
      {
      // inauguration day is Thursday 2005 January 20 noon Eastern Standard Time.
      TimeZone est = TimeZone.getTimeZone ( "America/New_York" );
      GregorianCalendar inauguration = new GregorianCalendar ( est );
      inauguration.set( 2005, Calendar.JANUARY, 20 , 12, 0, 0 );

      // locale specific: e.g.Jan 20, 2005
      DateFormat df = DateFormat.getDateInstance();

      // set timezone
      df.setCalendar( inauguration );

      // set timestamp
      String dateString = df.format( inauguration.getTime());
      System.out.println( dateString );
      }
   }

Displaying A Date With Precise Control

If you want precise control of how your date looks, you can use a mask like this:

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;

// display inauguration day as a String
public class Inauguration2
   {
   static public void main (String [] args)
      {
      // inauguration day is Thursday 2005 January 20 noon Eastern Standard Time.
      TimeZone est = TimeZone.getTimeZone ( "America/New_York" );
      GregorianCalendar inauguration = new GregorianCalendar ( est );
      inauguration.set(2005 , Calendar.JANUARY, 20, 12, 0, 0 );

      // mask for: Thursday 2005/01/20 12:00:00 PM EST : Eastern Standard Time
      // See below for link to description of all possible mask characters
      // and their meanings.
      SimpleDateFormat sdf = new SimpleDateFormat ( "EEEE yyyy/MM/dd hh:mm:ss aa zz : zzzzzz" );

      // set timezone
      sdf.setCalendar( inauguration );

      // set timestamp
      String dateString = sdf.format( inauguration.getTime() );
      System.out.println( dateString );
      }
   }

Complete List of SimpleDateFormat Mask Characters : available:

Parsing A Date

To convert a Date from a String to internal format is quite a production. Here is one way of doing it:


view

Notes:

Elapsed Time In Hours Between Two Timestamps

Have a look at this example program to calculate how many hours until the next presidential inauguration.

import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;

// Hours until the next presidential inauguration
public class Inauguration4
   {
   static final int MILLIS_PER_HOUR = 60 * 60 * 1000;
   static public void main ( String [] args )
      {
      // inauguration day is Thursday 2005 January 20 noon Eastern Standard Time.
      TimeZone est = TimeZone.getTimeZone ( "America/New_York" );
      GregorianCalendar inauguration = new GregorianCalendar ( est );
      inauguration.set( 2005 , Calendar.JANUARY, 20, 12, 0, 0 );

      // now is current time, using default timezone
      GregorianCalendar now = new GregorianCalendar();

      // milliseconds since 1970 Jan 1
      long epochInauguration = inauguration.getTime().getTime();
      long epochNow = now.getTime().getTime();

      double hours = (double) ( epochInauguration - epochNow ) /MILLIS_PER_HOUR;
      System.out.println( hours + " hours until the inauguration." );
      }
   }

Notes:

How Long Until Christmas, Daddy?

This sounds like a simple problem. Programmers posted many different solutions to the comp.lang.java.programmer newsgroup before before the gurus stopped finding holes in the logic. Part of the problem is that the question can have many different answers. I show eight plausible solutions here:


view

Taking A Timestamp Apart

//taking a timestamp apart using default timezone.
GregorianCalendar cal = new GregorianCalendar();
cal.setTimeInMillis( timestamp );
int year = cal.get( Calendar.YEAR );
int month = cal.get( Calendar.MONTH ) + 1;
int day = cal.get( Calendar.DAY_OF_MONTH );
int hour24 = cal.get( Calendar.HOUR_OF_DAY );
int hour12 = cal.get( Calendar.HOUR );
int amIs0OrPmIs1 = cal.get( Calendar.AM_PM );
int minute = cal.get( Calendar.MINUTE );
int second = cal.get( Calendar.SECOND );

Building A Timestamp from the Pieces

// buiding a timestamp using default timezone.
GregorianCalendar stamp = new GregorianCalendar();
stamp.clear();
stamp.set( year, month-1, day, hour, minute, second );
longtimestamp = stamp.getTimeInMillis();

Gotchas

java.util.GregorianCalendar has far fewer bugs and gotchas than the old java.util.Date class but it is still no picnic.

Learning More

The calendar classes are full of surprises. To learn more about them see http://mindprod.com/gotchas.html#DATE.

Dealing with pure dates is much simpler using the BigDate class. You can download it from http://mindprod.com/products.html#BIGDATE

TimeZones

Here is a list of available timezones:

Standard/(DaylightSaving) TimeZone

Add column 1 in hours to UTC to get local standard time.
Add column 2 in hours to UTC to get local daylight saving time.
Use UTC when you want no timezone at all.


CMP logo
CMP_home
home
Canadian Mind Products CSS
HTML Checked!
ICRA ratings logo
mindprod.com IP:[24.87.56.253]
Your IP:[80.134.30.163]
You are visitor number 26248.
Please send errors, omissions and suggestions
to improve this page to Roedy Green.
You can get a fresh copy of this page from: or possibly from your local J: drive mirror:
http://mindprod.com/jgloss/calendar.html J:\mindprod\jgloss\calendar.html