Thursday 23 March 2017

Calendar, GregorianCalendar & TimeZone - Java Tutorials

Calendar

The abstract Calendar class provides a set of methods that allows you to convert a time in milliseconds to a number of useful components. Some examples of the type of information that can be provided are: year, month, day, hour, minute, and second. It is intended that subclasses of Calendar will provide the specific functionality to interpret time information according to their own rules. This is one aspect of the Java class library that enables you to write programs that can operate in several international environments. An example of such a subclass is GregorianCalendar.

Calendar provides no public constructors. Calendar defines several protected instance variables. areFieldsSet is a boolean that indicates if the time components have been set. fields is an array of ints that holds the components of the time. isSet is a boolean array that indicates if a specific time component has been set. time is a long that holds the current time for this object. isTimeSet is a boolean that indicates if the current time has been set.

Calendar defines the following int constants, which are used when you get or set components of the calendar:

AM 
FRIDAY 
PM
AM_PM 
HOUR 
SATURDAY
APRIL 
HOUR_OF_DAY 
SECOND
AUGUST 
JANUARY 
SEPTEMBER
DATE 
JULY 
SUNDAY
DAY_OF_MONTH 
JUNE 
THURSDAY
DAY_OF_WEEK 
MARCH 
TUESDAY
DAY_OF_WEEK_IN_MONTH 
MAY 
UNDECIMBER
DAY_OF_YEAR 
MILLISECOND 
WEDNESDAY
DECEMBER 
MINUTE 
WEEK_OF_MONTH
DST_OFFSET 
MONDAY 
WEEK_OF_YEAR
ERA 
MONTH 
YEAR
FEBRUARY 
NOVEMBER 
ZONE_OFFSET
FIELD_COUNT
OCTOBER


Commonly Used Methods Defined by Calendar

abstract void add(int which, int val):  Adds val to the time or date component specified by which. To subtract, add a negative value. which must be one of the fields defined by Calendar, such as Calendar.HOUR.

boolean after(Object calendarObj):  Returns true if the invoking Calendar object contains a date that is later than the one specified by calendarObj. Otherwise, it returns false.

boolean before(Object calendarObj):  Returns true if the invoking Calendar object contains a date that is earlier than the one specified by calendarObj. Otherwise, it returns false.

final void clear( ):  Zeros all time components in the invoking object.

final void clear(int which):  Zeros the time component specified by which in the invoking object.

Object clone( ):  Returns a duplicate of the invoking object.

boolean equals(Object calendarObj):  Returns true if the invoking Calendar object contains a date that is equal to the one specified by calendarObj. Otherwise, it returns false.

int get(int calendarField):  Returns the value of one component of the invoking object. The component is indicated by calendarField. Examples of the components that can be requested are Calendar.YEAR, Calendar.MONTH, Calendar.MINUTE, and so forth.

static Locale[ ] getAvailableLocales( ):  Returns an array of Locale objects that contains the locales for which calendars are available.

static Calendar getInstance( ):  Returns a Calendar object for the default locale and time zone.

static Calendar getInstance(TimeZone tz):  Returns a Calendar object for the time zone specified by tz. The default locale is used.

static Calendar getInstance(Locale locale):  Returns a Calendar object for the locale specified by locale. The default time zone is used.

static Calendar getInstance(TimeZone tz, Locale locale):  Returns a Calendar object for the time zone specified by tz and the locale specified by locale.

final Date getTime( ):  Returns a Date object equivalent to the time of the invoking object.

TimeZone getTimeZone( ):  Returns the time zone for the invoking object.

final boolean isSet(int which):  Returns true if the specified time component is set. Otherwise, it returns false.

void set(int which, int val):  Sets the date or time component specified by which to the value specified by val in the invoking object. which must be one of the fields defined by Calendar, such as Calendar.HOUR.

final void set(int year, int month, int dayOfMonth):  Sets various date and time components of the invoking object.

final void set(int year, int month, int dayOfMonth, int hours, int minutes):  Sets various date and time components of the invoking object.

final void set(int year, int month, int dayOfMonth, int hours, int minutes, int seconds):  Sets various date and time components of the invoking object.

final void setTime(Date d):  Sets various date and time components of the invoking object. This information is obtained from the Date object d.

void setTimeZone(TimeZone tz):  Sets the time zone for the invoking object to that specified by tz.


The following program demonstrates several Calendar methods:

  // Demonstrate Calendar
  import java.util.Calendar;

  class CalendarDemo {
    public static void main(String args[]) {
      String months[] = {
              "Jan", "Feb", "Mar", "Apr",
              "May", "Jun", "Jul", "Aug",
              "Sep", "Oct", "Nov", "Dec"};

      // Create a calendar initialized with the
      // current date and time in the default
      // locale and timezone.
      Calendar calendar = Calendar.getInstance();

      // Display current time and date information.
      System.out.print("Date: ");
      System.out.print(months[calendar.get(Calendar.MONTH)]);
      System.out.print(" " + calendar.get(Calendar.DATE) + " ");
      System.out.println(calendar.get(Calendar.YEAR));

      System.out.print("Time: ");
      System.out.print(calendar.get(Calendar.HOUR) + ":");
      System.out.print(calendar.get(Calendar.MINUTE) + ":");
      System.out.println(calendar.get(Calendar.SECOND));

      // Set the time and date information and display it.
      calendar.set(Calendar.HOUR, 10);
      calendar.set(Calendar.MINUTE, 29);
      calendar.set(Calendar.SECOND, 22);

      System.out.print("Updated time: ");
      System.out.print(calendar.get(Calendar.HOUR) + ":");
      System.out.print(calendar.get(Calendar.MINUTE) + ":");
      System.out.println(calendar.get(Calendar.SECOND));
    }
  }

Sample output is shown here:

  Date: Apr 22 2002
  Time: 11:24:25
  Updated time: 10:29:22




GregorianCalendar

GregorianCalendar is a concrete implementation of a Calendar that implements the normal Gregorian calendar with which you are familiar. The getInstance( ) method of Calendar returns a GregorianCalendar initialized with the current date and time in the default locale and time zone.

GregorianCalendar defines two fields: AD and BC. These represent the two eras defined by the Gregorian calendar.

There are also several constructors for GregorianCalendar objects. The default, GregorianCalendar( ), initializes the object with the current date and time in the default locale and time zone. Three more constructors offer increasing levels of specificity:

      GregorianCalendar(int year, int month, int dayOfMonth)
      GregorianCalendar(int year, int month, int dayOfMonth, int hours,
                                      int minutes)
      GregorianCalendar(int year, int month, int dayOfMonth, int hours,
                                      int minutes, int seconds)

All three versions set the day, month, and year. Here, year specifies the number of years that have elapsed since 1900. The month is specified by month, with zero indicating January. The day of the month is specified by dayOfMonth. The first version sets the time to midnight. The second version also sets the hours and the minutes. The third version adds seconds.

You can also construct a GregorianCalendar object by specifying either the locale and/or time zone. The following constructors create objects initialized with the current date and time using the specified time zone and/or locale:

      GregorianCalendar(Locale locale)
      GregorianCalendar(TimeZone timeZone)
      GregorianCalendar(TimeZone timeZone, Locale locale)

GregorianCalendar provides an implementation of all the abstract methods in Calendar. It also provides some additional methods. Perhaps the most interesting is isLeapYear( ), which tests if the year is a leap year. Its form is

      boolean isLeapYear(int year)

This method returns true if year is a leap year and false otherwise.

The following program demonstrates GregorianCalendar:

  // Demonstrate GregorianCalendar
  import java.util.*;

  class GregorianCalendarDemo {
    public static void main(String args[]) {
      String months[] = {
              "Jan", "Feb", "Mar", "Apr",
              "May", "Jun", "Jul", "Aug",
              "Sep", "Oct", "Nov", "Dec"};
      int year;

      // Create a Gregorian calendar initialized
      // with the current date and time in the
      // default locale and timezone.
      GregorianCalendar gcalendar = new GregorianCalendar();

      // Display current time and date information.
      System.out.print("Date: ");
      System.out.print(months[gcalendar.get(Calendar.MONTH)]);
      System.out.print(" " + gcalendar.get(Calendar.DATE) + " ");
      System.out.println(year = gcalendar.get(Calendar.YEAR));

      System.out.print("Time: ");
      System.out.print(gcalendar.get(Calendar.HOUR) + ":");
      System.out.print(gcalendar.get(Calendar.MINUTE) + ":");
      System.out.println(gcalendar.get(Calendar.SECOND));

      // Test if the current year is a leap year
      if(gcalendar.isLeapYear(year)) {
        System.out.println("The current year is a leap year");
      }
      else {
        System.out.println("The current year is not a leap year");
      }
    }
  }

Sample output is shown here:

  Date: Apr 22 2002
  Time: 11:25:27
  The current year is not a leap year




TimeZone

Another time-related class is TimeZone. The TimeZone class allows you to work with time zone offsets from Greenwich mean time (GMT), also referred to as Coordinated Universal Time (UTC). It also computes daylight saving time. TimeZone only supplies the default constructor.


Some of the Methods Defined by TimeZone

Object clone( ):  Returns a TimeZone-specific version of clone( ).

static String[ ] getAvailableIDs( ):  Returns an array of String objects representing the names of all time zones.

static String[ ] getAvailableIDs(int timeDelta):  Returns an array of String objects representing the names of all time zones that are timeDelta offset from GMT.

static TimeZone getDefault( ):  Returns a TimeZone object that represents the default time zone used on the host computer.

String getID( ):  Returns the name of the invoking TimeZone object.

abstract int getOffset(int era, int year, int month, int dayOfMonth, int dayOfWeek, int millisec):  Returns the offset that should be added to GMT to compute local time. This value is adjusted for daylight saving time. The parameters to the method represent date and time components.

abstract int getRawOffset( ):  Returns the raw offset that should be added to GMT to compute local time. This value is not adjusted for daylight saving time.

static TimeZone getTimeZone(String tzName):  Returns the TimeZone object for the time zone named tzName.

abstract boolean inDaylightTime(Date d):  Returns true if the date represented by d is in daylight saving time in the invoking object. Otherwise, it returns false.

static void setDefault(TimeZone tz):  Sets the default time zone to be used on this host. tz is a reference to the TimeZone object to be used.

void setID(String tzName):  Sets the name of the time zone (that is, its ID) to that specified by tzName.

abstract void setRawOffset(int millis):  Sets the offset in milliseconds from GMT.

abstract boolean useDaylightTime( ):  Returns true if the invoking object uses daylight saving time. Otherwise, it returns false.

No comments:

Post a Comment