|
|
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
The previous section, Using Predefined Formats, described the formatting styles provided by theDateFormatclass. In most cases these predefined formats are adequate. However, if you want to create your own customized formats, you can use theSimpleDateFormatclass.
The code examples that follow demonstrate the methods of the
SimpleDateFormatclass. You can find the full source code for the examples in the file namedSimpleDateFormatDemo.
When you create aSimpleDateFormatobject, you specify a patternString. The contents of the patternStringdetermine the format of the date and time. For a full description of the pattern's syntax, see the tables in Date Format Pattern Syntax.The following code formats a date and time according to the pattern
Stringpassed to theSimpleDateFormatconstructor. TheStringreturned by theformatmethod contains the formatted date and time that are to be displayed.Date today; String output; SimpleDateFormat formatter; formatter = new SimpleDateFormat(pattern, currentLocale); today = new Date(); output = formatter.format(today); System.out.println(pattern + " " + output);The following table shows the output generated by the previous code example when the U.S.
Localeis specified:
Customized Date and Time Formats
Pattern Output dd.MM.yy 09.04.98 yyyy.MM.dd G 'at' hh:mm:ss z 1998.04.09 AD at 06:15:55 PDT EEE, MMM d, ''yy Thu, Apr 9, '98 h:mm a 6:15 PM H:mm 18:15 H:mm:ss:SSS 18:15:55:624 K:mm a,z 6:15 PM,PDT yyyy.MMMMM.dd GGG hh:mm aaa 1998.April.09 AD 06:15 PM
TheSimpleDateFormatclass is locale-sensitive. If you instantiateSimpleDateFormatwithout aLocaleparameter, it will format the date and time according to the defaultLocale. Both the pattern and theLocaledetermine the format. For the same pattern,SimpleDateFormatmay format a date and time differently if theLocalevaries.In the example code that follows, the pattern is hardcoded in the statement that creates the
SimpleDateFormatobject:Date today; String result; SimpleDateFormat formatter; formatter = new SimpleDateFormat("EEE d MMM yy", currentLocale); today = new Date(); result = formatter.format(today); System.out.println("Locale: " + currentLocale.toString()); System.out.println("Result: " + result);When the
currentLocaleis set to different values, the preceding code example generates this output:Locale: fr_FR Result: ven 10 avr 98 Locale: de_DE Result: Fr 10 Apr 98 Locale: en_US Result: Thu 9 Apr 98
|
|
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2004 Sun Microsystems, Inc. All rights reserved.