![]() |
The Java Developers Almanac 1.4 |
|
e316. Formatting the Time Using a Custom FormatA pattern of special characters is used to specify the format of the time. This example demonstrates some of the characters. For a complete listing, see the javadoc documentation for theSimpleDateFormat class.
Note: This example formats dates using the default locale
(which, in the author's case, is Format formatter;
// The hour (1-12)
formatter = new SimpleDateFormat("h"); // 8
formatter = new SimpleDateFormat("hh"); // 08
// The hour (0-23)
formatter = new SimpleDateFormat("H"); // 8
formatter = new SimpleDateFormat("HH"); // 08
// The minutes
formatter = new SimpleDateFormat("m"); // 7
formatter = new SimpleDateFormat("mm"); // 07
// The seconds
formatter = new SimpleDateFormat("s"); // 3
formatter = new SimpleDateFormat("ss"); // 03
// The am/pm marker
formatter = new SimpleDateFormat("a"); // AM
// The time zone
formatter = new SimpleDateFormat("z"); // PST
formatter = new SimpleDateFormat("zzzz"); // Pacific Standard Time
formatter = new SimpleDateFormat("Z"); // -0800
// Get today's date
Date date = new Date();
// Some examples
formatter = new SimpleDateFormat("hh:mm:ss a");
String s = formatter.format(date);
// 01:12:53 AM
formatter = new SimpleDateFormat("HH.mm.ss");
s = formatter.format(date);
// 14.36.33
e318. Formatting and Parsing a Time for a Locale Using Default Formats e319. Formatting and Parsing a Time for a Locale
© 2002 Addison-Wesley. |