Murach's Java Programming
Murach's Java Programming
Description
• Year must be a four-digit integer.
• Month must be an integer from 0 to 11 with 0 being January and 11 being December.
• Day must be an integer from 1 to 31.
• Hour must be an integer from 0 to 23, with 0 being 12 AM (midnight) and 23 being
11PM.
• Minute and second must be integers from 0 to 59.
Figure 13-1 How to use the GregorianCalendar class to set dates and times
408 Section 3 More Java essentials
Note
• For more information about these and other fields and methods, look up the Calen
dar and GregorianCalendar classes in the documentation for the Java API.
Figure 13-2 How to use the Calendar and GregorianCalendar fields and methods
410 Section 3 More Java essentials
Common constructors
Constructor Description
Date () Creates a Date object for the current date and time based
on your computer’s internal clock.
D a t e ( l o n g M i l li s e c o n d s ) Creates a Date object based on the number of milliseconds
that is passed to it.
Common methods
Method Description
getTime () Returns a long value that represents the number of milliseconds for the date.
toString () Returns a String object that contains the date and time formatted like this:
Wed Aug 04 08:31:25 PDT 2009.
Example 2: A statement that gets a Date object for the current date/time
Date now = new D a t eO ;
Example 4: Code that calculates the number of days between two dates
Date startDate = gregStartDate.getTime();
Date endDate = gregEndDate.getTime();
long startDateMS = startDate.getTime();
long endDateMS = endDate.getTime();
long elapsedMS = endDateMS - startDateMS;
long elapsedDays = elapsedMS / (24 * 60 * 60 * 1000) ;
Description
• A Date object stores a date and time as the number of milliseconds since January 1,
1970 00:00:00 GMT (Greenwich Mean Time).
• You need to convert GregorianCalendar objects to Date objects when you want to
use the DateFormat class to format them as shown in the next figure.
• Date objects are also useful when you want to calculate the number of milliseconds
(or days) between two dates.
Common fields
Style Date example Time example
SHORT 12/31/10 12:00 AM
MEDIUM Dec 31, 2010 7:30:00 PM
LONG December 31, 2010 7:30:00 AM PST
FULL Saturday, December 31, 2010 7:30:00 AM PST
Common method
Method Description
format (Date) Returns a String object of the Date object with the
format that’s specified by the DateFormat object.
Example 3: Code that overrides the default date and time formats
DateFormat shortDate = DateFormat.getDatelnstance(DateFormat.SHORT);
DateFormat shortTime = DateFormat.getTimelnstance(DateFormat.SHORT);
DateFormat shortDateTime =
DateFormat.getDateTimelnstance(DateFormat.SHORT, DateFormat.SHORT);
Description
• You can use the DateFormat class to format Date objects in various ways.
Figure 13-4 How to use the DateFormat class to format dates and times
414 Section 3 More Java essentials
Resulting output
f( Today is July 11, 2011 ^
II There are 166 days until Christmas. J
Figure 13-5 A DateUtils class that provides methods for handling dates
416 Section 3 More Java essentials
public Invoice()
{
lineltems = new A r r a y L i s t o () ;
invoiceDate = DateUtils.getCurrentDate();
}
public ArrayList<LineItem> getLinelterns()
{
return lineltems;
}
public void addltem(Lineltem lineltem)
{
this.lineltems.add(lineltem);
}
public double getlnvoiceTotal()
{
double invoiceTotal = 0 ;
for (Lineltem lineltem : this.lineltems)
{
invoiceTotal += lineltem.getTotal();
}
return invoiceTotal;
}
public String getFormattedTotal()
{
NUmberFormat currency = NumberFormat.getCurrencylnstance();
return currency.format(this.getlnvoiceTotal());
}
public Date getlnvoiceDate()
{
return invoiceDate;
}
public String getFormattedDate()
{
DateFormat shortDate = DateFormat.getDatelnstance(DateFormat.SHORT);
return shortDate.format(invoiceDate);
}
}
Notes
• For the third constructor shown above, the characters referred to by the intOffset
and intLength arguments must fall within the array. Otherwise, the constructor will
throw an IndexOutOfBoundsException.
• A char data type contains a single Unicode character, which is stored in two bytes.
When you use the second and third constructors above, you can construct a String
object from an array of char types. To code a literal char value, you use single
quotes instead of double quotes as shown in the third example.
• Because a byte data type can hold the Unicode value for every character in the
ASCII character set, you can also construct a String object from an array of bytes
as shown in the fourth example.
• Since String objects are immutable, they can’t grow or shrink. Later in this chapter,
you’ll learn how to work with StringBuilder objects that can grow and shrink.
Description
• StringBuilder objects are mutable, which means you can modify the characters in the
string. The capacity of a StringBuilder object is automatically increased if necessary.
• The append and insert methods accept primitive types, objects, and arrays of characters.
• The StringBuilder class was introduced with Java 1.5. It’s designed to replace the older
StringBuffer class, which has identical constructors and methods but isn’t as efficient.
Figure 13-11 Code examples that work with the StringBuilder class
428 Section 3 More Java essentials
Perspective
Now that you’ve finished this chapter, you should be able to use the
classes provided by the Java API to work with dates, and you should be able to
use the String and StringBuilder classes to work with strings. These are skills
that you will use often as you develop Java applications.
Summary
• You can use the GregorianCalendar, Calendar, Date, and DateFormat classes to
create, manipulate, and format dates and times.
• You can use methods of the String class to locate a string within another string,
return parts of a string, and compare all or part of a string. However, String objects
are immutable, so you can’t add, delete, or modify individual characters in a string.
• StringBuilder objects are mutable, so you can use the StringBuilder methods to
add, delete, or modify characters in a StringBuilder object. Whenever necessary,
Java automatically increases the capacity of a StringBuilder object.
For this exercise, you’ll modify the Invoice class that’s shown in figure 13-6 so
it contains methods that return a due date, calculated as 30 days after the invoice
date. Then, you’ll modify the Invoice application that was shown in chapter 12
to display the invoice date and due date for a batch of invoices.
1. Open the project named chl3_exl_Invoice that’s in the ex_starts directory.
Then, review the code in the Invoice and InvoiceApp classes.
2. Add two methods named getDueDate and getFormattedDueDate to the
Invoice class. The getDueDate method should calculate and return a Date
object that’s 30 days after the invoice date. The getFormattedDueDate method
should return the due date in the short date format.
3. Modify the displaylnvoices method in the InvoiceApp class so that the invoice
display includes columns for the invoice date and the due date in addition to
the invoice number and total. Then, run the application to make sure it works.
Chapter 13 How to work with dates and strings 429
3. Display each word of the name on a separate line. If the user enters fewer
than two words or more than three words, display an error message. Also,
make sure the application works even if the user enters one or more spaces
before or after the name.
4. Test the project to make sure it works correctly.