Java Reference
In-Depth Information
Table 12-6. ( continued )
Symbol
Description
Examples
'
'Hello'
Hello
Escape for text
Text within single quotes is output directly. To output a
single quote, use two consecutive single quotes.
'Hello' MMMM
Hello July
''
'''Hello''' MMMM
'Hello' July
A single quote
[ ] An optional section
Please refer to the discussion for an example.
#, {, } They are reserved for future use.
You can have optional sections in a pattern string. The symbols [ and ] denote the start and the end of an
optional section, respectively. A pattern enclosed within an optional section is output only if information is available
for all its elements. Otherwise, an optional section is skipped. An optional section may be nested inside another
optional section. Listing 12-23 shows how to use an optional section in a pattern. The optional section contains time
information. When you format a date, the optional section is skipped.
Listing 12-23. Using an Optional Section in a Datetime Formatting Pattern
// OptionalSectionTest.java
package com.jdojo.datetime;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Month;
import java.time.format.DateTimeFormatter;
public class OptionalSectionTest {
public static void main(String[] args) {
// A pattern with an optional section
String pattern = "MM/dd/yyyy[ 'at' HH:mm:ss]";
DateTimeFormatter fmt = DateTimeFormatter.ofPattern(pattern);
LocalDate ld = LocalDate.of(2012, Month.MAY, 30);
LocalTime lt = LocalTime.of(17, 30, 12);
LocalDateTime ldt = LocalDateTime.of(ld,lt);
// Format a date. Optional section will be skipped because a
// date does not have time (HH, mm, and ss) information.
String str1 = fmt.format(ld);
System.out.println(str1);
// Format a datetime. Optional section will be output.
String str2 = fmt.format(ldt);
System.out.println(str2);
}
}
 
 
Search WWH ::




Custom Search