Java Reference
In-Depth Information
Tip
Use the Locale.getDefault() method to get the default Locale for your system.
If you want to use custom date formats, use the SimpleDateFormat class. Formatting using the SimpleDateFormat
class is locale-sensitive. Its default constructor creates a formatter with the default locale and default date format
for that locale. You can create a formatter using other constructors where you can specify your own date format and
locale. Once you have an object of the SimpleDateFormat class, you can call its format() method to format the date.
If you want to change the date format for subsequent formatting, you can use the applyPattern() method by passing
the new date format (or pattern) as an argument. For example,
// Create a formatter with a pattern dd/MM/yyyy. Note that uppercase M is used
// for month-of-year. Lowercase d denotes day in month, whereas uppercase D //denotes day in year
// Note that / in the date format will appears as /.
SimpleDateFormat simpleFormatter = new SimpleDateFormat("dd/MM/yyyy");
// Get current date
Date today = new Date();
// Format the current date
String formattedDate = simpleFormatter.format(today);
// Print the date
System.out.println("Today is (dd/MM/yyyy): " + formattedDate);
// Change the date format. Now month will be spelled fully.
// Note a comma will appear as a comma. It has no special interpretation.
simpleFormatter.applyPattern("MMMM dd, yyyy");
// Format the current date
formattedDate = simpleFormatter.format(today);
// Print the date
System.out.println("Today is (MMMM dd, yyyy): " + formattedDate);
Today is (dd/MM/yyyy): 24/01/2014
Today is (MMMM dd, yyyy): January 24, 2014
Note that the output will be different when you run this code on your computer. It will print the current date in
this format using the default locale. The above output is in the US locale.
Letters that are used to create patterns to format a date and time are listed with their meanings in Table 13-2 . The
examples are shown as if the date to display is July 10, 1996 at 12:30:55 in the afternoon.
 
 
Search WWH ::




Custom Search