CHARMINGTONLAPOINTES.INFO

Tits!!!!!!!!! d m y dating dateformat ass and

Java Programming Language

Date and Time - Creation, Operation and Formatting

Introduction

There are many Java classes available for date/time and it becomes pretty confusing, in particular, the and clases. The documentation is not very clear, and I have to look into the source codes to understand the salient features.

java.util.Date and java.text.SimpleDateFormat

is sufficient if you need only a current timestamp in your application, and you do not need to operate on dates, e.g., one-week later. You can further use to control the date/time display format.

The class represents a specific instance in time, with millisecond precision. It has two constructors:

  • : Allocate a instance with the current time.
  • : Allocate a instance with the given time.

From the source code, the no-arg constructor invokes to get the milliseconds since January 1, 1970, 00:00:00 GMT (known as "epoch") and stores in a private variable . Take note that epoch is absolute and does not depends on local time zones.

Most of the methods in are deprecated (for lack of internationalization support), except:

  • : returns the number of milliseconds since epoch.
  • : returns a date/time string in local time-zone using the default locale in the format: , where is the day of week (Sun, ..., Sat), is the month (Jan, ..., Dec), zzz is the time zone. Take note that although is represented based on the absolute epoch, the displays the local time, according to the default time zone.

The 's method has a fixed date/time display format. You can use to control the display format.

EXAMPLE:

import java.text.SimpleDateFormat; import java.util.Date; public class DateTest { public static void main(String[] args) { Date now = new Date(); System.out.println("toString(): " + now); SimpleDateFormat dateFormatter = new SimpleDateFormat("E, y-M-d 'at' h:m:s a z"); System.out.println("Format 1: " + dateFormatter.format(now)); dateFormatter = new SimpleDateFormat("E yyyy.MM.dd 'at' hh:mm:ss a zzz"); System.out.println("Format 2: " + dateFormatter.format(now)); dateFormatter = new SimpleDateFormat("EEEE, MMMM d, yyyy"); System.out.println("Format 3: " + dateFormatter.format(now)); } } toString(): Sat Sep 25 21:27:01 SGT 2010 Format 1: Sat, 10-9-25 at 9:27:1 PM SGT Format 2: Sat 2010.09.25 at 09:27:01 PM SGT Format 3: Saturday, September 25, 2010

Summary:

  • class is sufficient if you just need a simple timestamp.
  • You could use to control the date/time display format.

Use class if you need to extract year, month, day, hour, minute, and second, or manipulating these field (e.g., 7 days later, 3 weeks earlier).

Use to format a (form to text) and parse a date string (from text to ). is a subclass of .

is legacy class, which does not support internationalization. and support locale (you need to consider locale only if you program is to be run in many countries concurrently).

java.util.Calendar & java.util.GregorianCalendar

The class provides support for:

  1. maintaining a set of calendar fields such as , , , , , , ; and
  2. manipulating these calendar fields, such as getting the date of the previous week, roll forward by 3 days.

provides internationalization support.

is a abstract class, and you cannot use the constructor to create an instance. Instead, you use the static method to instantiate an implementation sub-class.

  • : return a instance based on the current time in the default time zone with the default locale.

Looking into the source code reveals that: returns a instance for all locales, (except for Thai ("") and for Japanese ("")).

The most important method in is , which produces an . The are defined as constant and includes:

  • : returns 1 () to 7 ().
  • year
  • : returns 0 () to 11 ().
  • , : 1 to 31
  • : 0 to 23
  • : 0 to 59
  • : 0 to 59
  • : 0 to 999
  • : 0 to 11, to be used together with .
  • : returns 0 () or 1 ().
  • : 1 through 7 always correspond to 1; 8 through 14 correspond to 2, and so on.
  • : 1 to 366
  • : GMT offset value of the time zone.
  • : Indicate AD (), BC ().

A date in can be represented as:

YEAR + MONTH + DAY_OF_MONTH YEAR + MONTH + WEEK_OF_MONTH + DAY_OF_WEEK YEAR + MONTH + DAY_OF_WEEK_IN_MONTH + DAY_OF_WEEK YEAR + DAY_OF_YEAR YEAR + DAY_OF_WEEK + WEEK_OF_YEAR

A time in can be represented as:

HOUR_OF_DAY AM_PM + HOUR

Example:

import java.util.Calendar; public class GetYMDHMS { public static void main(String[] args) { Calendar cal = Calendar.getInstance(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH); int day = cal.get(Calendar.DAY_OF_MONTH); int hour = cal.get(Calendar.HOUR_OF_DAY); int minute = cal.get(Calendar.MINUTE); int second = cal.get(Calendar.SECOND); System.out.printf("Now is %4d/%02d/%02d %02d:%02d:%02d\n", year, month+1, day, hour, minute, second); } }

has these setters and operations:

  • : Adds or subtracts the specified amount of time to the given calendar field, based on the calendar's rules.
  • : Adds or subtracts (up/down) a single unit of time on the given time field without changing larger fields.
  • : Adds the specified (signed) amount to the specified calendar field without changing larger fields.

Other frequently-used methods are:

  • : return a object based on this 's value.
  • : Returns this time value in milliseconds.

Conversion between Calendar and Date

You can use and to convert between and .

Date getTime(): Returns a Date object representing this Calendar's time value void setTime(Date aDate): Sets this Calendar's time with the given Date instance

EXAMPLE:

import java.util.Date; import java.util.Calendar; import java.text.SimpleDateFormat; public class CalendarTest { public static void main(String[] args) { Calendar cal = Calendar.getInstance(); System.out.println("Calendar's toString() is : " + cal + "\n"); System.out.println("Time zone is: " + cal.getTimeZone() + "\n"); Date date = cal.getTime(); System.out.println("Current date and time in Date's toString() is : " + date + "\n"); System.out.println("Year : " + cal.get(Calendar.YEAR)); System.out.println("Month : " + cal.get(Calendar.MONTH)); System.out.println("Day of Month : " + cal.get(Calendar.DAY_OF_MONTH)); System.out.println("Day of Week : " + cal.get(Calendar.DAY_OF_WEEK)); System.out.println("Day of Year : " + cal.get(Calendar.DAY_OF_YEAR)); System.out.println("Week of Year : " + cal.get(Calendar.WEEK_OF_YEAR)); System.out.println("Week of Month : " + cal.get(Calendar.WEEK_OF_MONTH)); System.out.println("Day of the Week in Month : " + cal.get(Calendar.DAY_OF_WEEK_IN_MONTH)); System.out.println("Hour : " + cal.get(Calendar.HOUR)); System.out.println("AM PM : " + cal.get(Calendar.AM_PM)); System.out.println("Hour of the Day : " + cal.get(Calendar.HOUR_OF_DAY)); System.out.println("Minute : " + cal.get(Calendar.MINUTE)); System.out.println("Second : " + cal.get(Calendar.SECOND)); System.out.println(); Calendar calTemp; calTemp = (Calendar) cal.clone(); calTemp.add(Calendar.DAY_OF_YEAR, -365); System.out.println("365 days ago, it was: " + calTemp.getTime()); calTemp = (Calendar) cal.clone(); calTemp.add(Calendar.HOUR_OF_DAY, 11); System.out.println("After 11 hours, it will be: " + calTemp.getTime()); calTemp = (Calendar) cal.clone(); calTemp.roll(Calendar.HOUR_OF_DAY, 11); System.out.println("Roll 11 hours, it will be: " + calTemp.getTime()); System.out.println(); } }

java.util.GregorianCalendar

The calendar that we use today, called Gregorian calendar, came into effect in October 15, 1582 in some countries and later in other countries. It replaces the Julian calendar. 10 days were removed from the calendar, i.e., October 4, 1582 (Julian) was followed by October 15, 1582 (Gregorian). The only difference between the Gregorian and the Julian calendar is the "leap-year rule". In Julian calendar, every four years is a leap year. In Gregorian calendar, a leap year is a year that is divisible by 4 but not divisible by 100, or it is divisible by 400, i.e., the Gregorian calendar omits century years which are not divisible by 400 (removing 3 leap years (or 3 days) for every 400 years). Furthermore, Julian calendar considers the first day of the year as march 25th, instead of January 1st.

is an abstract class. returns an implementation class (except locales of "" and ""). In Java, this handles both the Gregorian calendar as well as the Julian calendar, including the cut over.

has the following constructors:

  • : using the current time, with the default time zone and locale.
  • : with the default time zone and locale.
  • : using current time.

For example,

Calendar cal1 = new GregorianCalendar(); Calendar cal2 = new GregorianCalendar(2010, 9, 26); cal2.get(Calendar.DAY_OF_WEEK);

java.text.DateFormat & java.text.SimpleDateFormat

Read Java Tutorial, Internationalization ⇒ Formatting ⇒ Dates and Times at http://java.sun.com/docs/books/tutorial/i18n/format/dateintro.html.

is an abstract class for formats (from date to text) and parses (from text to date) date/time in a text-language-independent manner. is an implementation subclass. Date formatter operates on object.

To use the date formatter, first create a object for the desired date/time format, and then use the method to produce a date/time string.

To use the , use one of these static factory method to create an instance:

  • : use the default style and locale to format date and time.
  • : style includes , , , and .
  • : uses style for date and time.
  • , : date only.
  • , : time only.

To parse a text string int , use:

DateFormat formatter = .... Date myDate = formatter.parse(myString);

EXAMPLE:

import java.util.Date; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Locale; public class DateFormatTest { public static void main(String[] args) { Date now = new Date(); System.out.println(now); DateFormat formatter = DateFormat.getInstance(); String dateStr = formatter.format(now); System.out.println(dateStr); formatter = DateFormat.getTimeInstance(); System.out.println(formatter.format(now)); formatter = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL, Locale.FRANCE); System.out.println(formatter.format(now)); SimpleDateFormat simpleFormatter = new SimpleDateFormat("E yyyy.MM.dd 'at' hh:mm:ss a zzz"); System.out.println(simpleFormatter.format(now)); } } Sun May 16 19:38:41 SGT 2010 5/16/10 7:38 PM 7:38:41 PM dimanche 16 mai 2010 19 h 38 SGT Sun 2010.05.16 at 07:38:41 PM SGT

Measuring Time

Many applications (such as games and animation) require good timing control.

Java provides these methods in class:

: Returns the current time in milliseconds since January 1, 1970 00:00:00 GMT (known as "epoch"), in .

long startTime = System.currentTimeMillis(); ....... long estimatedTime = System.currentTimeMillis() - startTime;

: Returns the current value of the most precise available system timer, in nanoseconds, in . Introduced in JDK 1.5. is meant for measuring relative time interval instead of providing absolute timing.

long startTime = System.nanoTime(); ....... long estimatedTime = System.nanoTime() - startTime;

Take note that milli is 10-3=0.001, nano is 10-9=0.000000001. There is no micro (10-6=0.000001) timer.

 

 

REFERENCES & RESOURCES

Latest version tested: JDK 1.6
Last modified: September, 2010

http://www3.ntu.edu.sg/home/ehchua/programming/java/DateTimeCalendar.html