Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Date;
public static void main(String[] args) { // Make a new Date object. It will be initialized to the current time. Date now = new Date();
// And the default time and date-time DateFormats System.out.println(" 3. " + DateFormat.getTimeInstance().format(now)); System.out.println(" 4. " + DateFormat.getDateTimeInstance().format(now));
// Next, try the short, medium and long variants of the // default time format System.out.println(" 5. " + DateFormat.getTimeInstance(DateFormat.SHORT).format(now)); System.out.println(" 6. " + DateFormat.getTimeInstance(DateFormat.MEDIUM).format(now)); System.out.println(" 7. " + DateFormat.getTimeInstance(DateFormat.LONG).format(now));
// For the default date-time format, the length of both the // date and time elements can be specified. Here are some examples: System.out.println(" 8. " + DateFormat.getDateTimeInstance( DateFormat.SHORT, DateFormat.SHORT).format(now)); System.out.println(" 9. " + DateFormat.getDateTimeInstance( DateFormat.MEDIUM, DateFormat.SHORT).format(now)); System.out.println("10. " + DateFormat.getDateTimeInstance(
DateFormat.LONG, DateFormat.LONG).format(now)); } }
Figure 1. Using default DateFormat objects to format a Date object. When you run this class, you will see output that looks something like that shown in Figure 2.
> java DateFormatExample1 1. Tue Nov 04 20:14:11 EST 2003 2. 11/4/03 8:14 PM 3. 8:14:11 PM 4. Nov 4, 2003 8:14:11 PM 5. 8:14 PM 6. 8:14:11 PM 7. 8:14:11 PM EST 8. 11/4/03 8:14 PM 9. Nov 4, 2003 8:14 PM 10. November 4, 2003 8:14:11 PM EST
Figure 2. Output from example in Figure 1 Default DateFormat objects retrieved from the static getInstance(),getTimeInstance(), and getDateTimeInstance() methods can also be used for parsing String objects to produce Date objects. Figure 3 shows a simple example of this.
public static void main(String[] args) { // Make a String that has a date in it, with MEDIUM date format // and SHORT time format. String dateString = "Nov 4, 2003 8:14 PM";
// Get the default MEDIUM/SHORT DateFormat DateFormat format = DateFormat.getDateTimeInstance( DateFormat.MEDIUM, DateFormat.SHORT);
// Parse the date try { Date date = format.parse(dateString); System.out.println("Original string: " + dateString); System.out.println("Parsed date : " + date.toString()); } catch(ParseException pe) { System.out.println("ERROR: could not parse date in string \"" + dateString + "\""); } } }
Figure 3. Using default DateFormat objects to parse a String The result is shown in Figure 4. Note that since the string version of the date did not contain timezone or seconds, the timezone is set to the default timezone (EST, in this case) and the seconds are set to zero.
> java DateFormatExample2 Original string: Nov 4, 2003 8:14 PM Parsed date : Tue Nov 04 20:14:00 EST 2003
Figure 4. Parsing a date string The parse method throws an exception if a date matching the format cannot be parsed. In the code shown in Figure 3, the string matches the format exactly. To see what happens when a bad string is encountered, the class in Figure 5 reads and attempts to parse input until a blank line (or a Control-D) is entered.
import java.text.DateFormat; import java.text.ParseException; import java.util.Date; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader;
public static void main(String[] args) { // Get the default MEDIUM/SHORT DateFormat DateFormat format = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT);
// Read and parse input, stopping on a blank input line BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); try { System.out.print("ENTER DATE STRING: "); String dateString = reader.readLine();
while ((dateString != null) && (dateString.length() > 0)) { // Parse the date try { Date date = format.parse(dateString); System.out.println("Original string: " + dateString); System.out.println("Parsed date : " + date.toString());
System.out.println(); // Skip a line } catch(ParseException pe) { System.out.println( "ERROR: could not parse date in string \"" + dateString + "\""); }
// Read another string System.out.print("ENTER DATE STRING: "); dateString = reader.readLine(); } } catch(IOException ioe) { System.out.println("I/O Exception: " + ioe); } } }
Figure 5. Example of parsing dates entered on the command line Figure 6 shows an example of running this class and entering several date strings. (Text entered is shown in italics.)
> java DateFormatExample3 ENTER DATE STRING: Nov 4, 2003 8:14 PM Original string: Nov 4, 2003 8:14 PM Parsed date : Tue Nov 04 20:14:00 EST 2003
ENTER DATE STRING: Nov 4, 2003 8:14 ERROR: could not parse date in string "Nov 4, 2003 8:14 "
ENTER DATE STRING: Nov 4, 2003 8:14 AM Original string: Nov 4, 2003 8:14 AM Parsed date : Tue Nov 04 08:14:00 EST 2003
ENTER DATE STRING: November 4, 2003 8:14 AM Original string: November 4, 2003 8:14 AM Parsed date : Tue Nov 04 08:14:00 EST 2003
ENTER DATE STRING: Nov 4, 2003 20:14 PM Original string: Nov 4, 2003 20:14 PM Parsed date : Wed Nov 05 08:14:00 EST 2003
ENTER DATE STRING: Nov 4, 2003 20:14 ERROR: could not parse date in string "Nov 4, 2003 20:14"
Figure 6. Parsing a variety of date strings Note that the default parser is somewhat flexible. It recognizes a long version of the month name (November instead of Nov), but does not recognize the two dates shown in red, both of which are missing AM or PM. Furthermore, it produces possibly unexpected results when the time 20:14 PM is entered: The parsed date is 8:14 the next morning. DateFormat actually gives you a small amount of control over leniency in parsing. The default DateFormat instances are lenient by default, but invoking format.setLenient(false); in the example in Figure 5 would cause the 20:14 PM example (in Figure 6) to fail, though it will still accept November or Nov. Using SimpleDateFormat for custom date formatting and parsing The default DateFormat instances returned by the static methods in theDateFormat class may be sufficient for many purposes, but clearly do not cover all possible valid or useful formats for dates. For example, notice that in Figure 2, none of the DateFormat-generated strings (numbers 2 9) match the format of the output of the Date classs toString() method. This means that you cannot use the default DateFormat instances to parse the output of toString(), something that might be useful for things like parsing log data. The SimpleDateFormat lets you build custom formats. Dates are constructed with a string that specifies a pattern for the dates to be formatted and/or parsed. From the SimpleDateFormat JavaDocs, the characters in Figure 7 can
be used in date formats. Where appropriate, 4 or more of the character will be interpreted to mean that the long format of the element should be used, while fewer than 4 mean that a short format should be used.
Symbol G y
Month
Text or Number
Day in month
Number
d -> 3 dd -> 03 h -> 3 hh -> 03 H -> 15 HH -> 15 k -> 3 kk -> 03 K -> 15 KK -> 15 m -> 7
Number
Hour (0-23)
Number
Hour (1-24)
Number
Number
Minute
Number
m -> 15 mm -> 15
s S E
s -> 15 ss -> 15 SSS -> 007 EEE -> Tue EEEE -> Tuesday D -> 65 DDD -> 065 F -> 1
D F
Number Number
w W a
Time zone
Text
Delimiter Literal
Figure 7. Syntax elements for SimpleDateFormat Note that you will generally never want to use single-digit minutes, seconds, or milliseconds, even though these are supported bySimpleDateFormat (m, s, S). Using the syntax from Figure 7, we can now make a SimpleDateFormatthat can read the output of Date.toString(). Figure 8 shows an example this:
public static void main(String[] args) { // Make a new Date object. It will be initialized to the // current time. Date now = new Date();
// Print the result of toString() String dateString = now.toString(); System.out.println(" 1. " + dateString);
// Make a SimpleDateFormat for toString()'s output. This // has short (text) date, a space, short (text) month, a space, // 2-digit date, a space, hour (0-23), minute, second, a space, // short timezone, a final space, and a long year. SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
// See if we can parse the output of Date.toString() try { Date parsed = format.parse(dateString); System.out.println(" 2. " + parsed.toString()); } catch(ParseException pe) { System.out.println("ERROR: Cannot parse \"" + dateString + "\""); }
// Print the result of formatting the now Date to see if the result // is the same as the output of toString() System.out.println(" 3. " + format.format(now)); } } The output shows three identical strings:
> java DateFormatExample4 1. Tue Nov 04 21:53:43 EST 2003 2. Tue Nov 04 21:53:43 EST 2003 3. Tue Nov 04 21:53:43 EST 2003