Java Reference
In-Depth Information
// Format dates using the ISO_DATE formatter
String ldStr = ISO_DATE.format(LocalDate.now());
String odtStr = ISO_DATE.format(OffsetDateTime.now());
String zdtStr = ISO_DATE.format(ZonedDateTime.now());
System.out.println("Local Date; " + ldStr);
System.out.println("Offset Datetime: " + odtStr);
System.out.println("Zoned Datetime: " + zdtStr);
Local Date; 2014-01-09
Offset Datetime: 2014-01-09-06:00
Zoned Datetime: 2014-01-09-06:00
Pay attention to the names of the predefined formatters. The datetime object being formatted must contain
the components as suggested by their names. For example, the ISO_DATE formatter expects the presence of the date
components, and hence, it should be not used to format time-only objects such as a LocalTime . Similarly, the
SIO_TIME formatter should be used to format a LocalDate .
// A runtime error as a LocalTime does not contain date components
String ltStr = ISO_DATE.format(LocalTime.now());
Using the format( ) Method of Datetime Classes
You can format a datetime object using its format() method. The format() method takes an object of the
DateTimeFormatter class. The following snippet of code uses this approach. The ISO_DATE formatter is used.
import java.time.LocalDate;
import java.time.OffsetDateTime;
import java.time.ZonedDateTime;
import static java.time.format.DateTimeFormatter.ISO_DATE;
...
LocalDate ld = LocalDate.now();
String ldStr = ld.format(ISO_DATE);
System.out.println("Local Date: " + ldStr);
OffsetDateTime odt = OffsetDateTime.now();
String odtStr = odt.format(ISO_DATE);
System.out.println("Offset Datetime: " + odtStr);
ZonedDateTime zdt = ZonedDateTime.now();
String zdtStr = zdt.format(ISO_DATE);
System.out.println("Zoned Datetime: " + zdtStr);
Local Date: 2014-01-09
Offset Datetime: 2014-01-09-06:00
Zoned Datetime: 2014-01-09-06:00
 
Search WWH ::




Custom Search