Java Reference
In-Depth Information
13.
Insert the following statements to define a birthday of January 23, 1991 and display it in the
SimpleDateFormat pattern (sdf ) defined earlier:
Calendar cal = Calendar.getInstance();
cal.set(1991, Calendar.JANUARY, 23);
Date bday = cal.getTime();
System.out.println(sdf.format(bday));
Notice in the second statement that the date is specified as year, month, and then day and that the Calendar
object's static fields (JANUARY, FEBRUARY, etc.) are used to specify the month. You can use numbers instead of the
month fields but beware: the numbers to specify the individual months begin at 0 and end at 11 (i.e., 0 for January, 1
for February, 11 for December). Boy, oh boy! Is that numbering sequence a potential source of error and confusion or
what?! That's why it is best to use the month fields.
14.
Save DateTimeApp and run as an application.
The results should be:
Thu Feb 17 14:42:02 EST 2011
01/23/1991
15.
Change the calendar set statement to the following and run the application.
cal.set(1988, Calendar. FEBRUARY , 30);
Bet you weren't expecting that. The calendar property lenient controls whether the date specified is validated.
The default is not to check (i.e., lenient is true), so we will change that.
16.
Change the calendar lenient property by adding the following on the line after the
calendar is created but before the date is set.
cal.setLenient( false );
17.
Run the application.
Notice in the console that an IllegalArgumentException was generated for the Month field.
18.
Change the day of the month to 29 and run the application.
Notice that 29 is valid for February 1988. This proves that Calendar takes into account leap years.
As you can probably tell, working with dates and times is a little awkward. This is a prime area for a company/
organization to create their own date and time classes to simplify and standardize formatting.
19.
Print out a copy of the DateTimeApp source code.
Tutorial: Formatting Currency
So far, we have been unsuccessful in using concatenation to format the employee salary and tax values. Let's apply
our newfound formatting knowledge to fix the application. First, we need to determine where the formatting should
be done. We had been formatting in EnterEmpInfo but formatting should be performed in Employee. Why? The
philosophy of object-oriented programming is to store all related data and functions in one object, in this case,
Employee. The EnterEmpInfo object's function is to receive and validate information about an Employee, not store
the information or provide Employee functions. Calculating the gross salary and tax amount has nothing to do with
entering employee information. These functions should be in Employee not EnterEmpInfo.
 
Search WWH ::




Custom Search