Thursday, March 19, 2009

Date-related classes in Java

There are lots of date-related classes in Java and my mind is going crazy determining which to use and how to use them. Here, I will attempt to explain some of the common classes and highlight what they can and cannot do. Most of the information is obtained from the Java API, unless otherwise stated.

Date class: "The class Date represents a specific instant in time, with millisecond precision."

This class is also slowly becoming deprecated, and there are limited useful functions available/recommended for use. These functions are:

Date()

Constructor; creates a Date object that represents the time now.

boolean after(Date when)

Returns true if this date is after the when date.

boolean before(Date when)

Returns true if this date is before the when date.

Calendar class: "The Calendar class is an abstract class that provides methods for converting between a specific instant in time and a set of calendar fields such as YEAR, MONTH, DAY_OF_MONTH, HOUR, and so on."

A Calendar object is different from a Date object because it is able to view the date as an element of the calendar, and thus the class provides functions to manipulate the object.

static
Calendar getInstance()

Calendar class is abstract, so use this to get a calendar using the default time zone and locale.

void add(int field, int amount)

Adds or subtracts the specified amount of time to the given calendar field.
E.g. To subtract 5 days from the current time of the calendar, you call: add(CALENDAR.DATE, -5)

boolean after(Object when)

Returns true if this date is after the when date.

boolean before(Object when)

Returns true if this date is before the when date.

SimpleDateFormat class: "SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner."

Here are some of the commonly used date and time patterns:

"yyyy.MM.dd"

2001.07.04

"EEE, MMM d, yy"

Wed, Jul 4, 01

"HH:mm:ss"

12:08:56

"h:mm a"

12:08 PM

These are useful functions related to this class:

SimpleDateFormat(String pattern)

Constructor; creates a SimpleDateFormat object using the given pattern.

Date parse(String text)

Parses text from a string to produce a Date.

Other date-related classes include DateFormat and GregorianCalendar.

No comments:

Post a Comment