Recipe 6.1 Finding Today s Date


Recipe 6.1 Finding Today's Date

Problem

You want to find today's date.

Solution

Use a Date object's toString( ) method.

Discussion

The quick and simple way to get today's date and time is to construct a Date object with no arguments in the constructor call, and call its toString( ) method:

// Date0.java  System.out.println(new java.util.Date( ));

However, for reasons just outlined, we want to use a Calendar object. Just use Calendar.getInstance( ).getTime( ) , which returns a Date object (even though the name makes it seem like it should return a Time value[1]) and prints the resulting Date object, using its toString( ) method or preferably a DateFormat object. You might be tempted to construct a GregorianCalendar object, using the no-argument constructor, but if you do this, your program will not give the correct answer when non-Western locales get Calendar subclasses of their own (which might occur in some future release of Java). The static factory method Calendar.getInstance( ) returns a localized Calendar subclass for the locale you are in. In North America and Europe it will likely return a GregorianCalendar, but in other parts of the world it might (someday) return a different kind of Calendar.

[1] Just to be clear: Date 's getTime( ) returns the time in seconds while Calendar's getTime( ) returns a Date.

Do not try to use a GregorianCalendar 's toString( ) method; the results are truly impressive, but not very interesting. Sun's implementation prints all its internal state information; Kaffe's inherits Object's toString( ), which just prints the class name and the hashcode. Neither is useful for our purposes.

C> java  Date1 java.util. GregorianCalendar[time=932363506950,areFieldsSet=true,areAllFieldsSet=true,lenient=tr ue,zone=java.util.SimpleTimeZone[id=America/Los_Angeles,offset=- 28800000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=3,startMonth=3,sta rtDay=1,startDayOfWeek=1,startTime=7200000,endMode=2,endMonth=9,endDay=- 1,endDayOfWeek=1,endTime=7200000],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEA R=1999,MONTH=6,WEEK_OF_YEAR=30,WEEK_OF_MONTH=4,DAY_OF_MONTH=18,DAY_OF_YEAR=199,DAY_ OF_WEEK=1,DAY_OF_WEEK_IN_MONTH=3,AM_PM=1,HOUR=10,HOUR_OF_ DAY=22,MINUTE=51,SECOND=46,MILLISECOND=950,ZONE_OFFSET=-28800000,DST_OFFSET=3600000]

Calendar's getTime( ) returns a Date object, which can be passed to println( ) to print today's date (and time) in the traditional (but non-localized) format:

// Date2.java  System.out.println(Calendar.getInstance( ).getTime( ));

To print the date in any other format, use java.text.DateFormat, which you'll meet in Recipe 6.2.



Java Cookbook
Java Cookbook, Second Edition
ISBN: 0596007019
EAN: 2147483647
Year: 2003
Pages: 409
Authors: Ian F Darwin

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net