Predefined formatters are defined as constants in
the DateTimeFormatter
class.
BASIC_ISO_DATE
ISO_DATE
ISO_TIME
ISO_DATE_TIME
ISO_INSTANT
ISO_LOCAL_DATE
ISO_LOCAL_TIME
ISO_LOCAL_DATE_TIME
ISO_OFFSET_DATE
ISO_OFFSET_TIME
ISO_OFFSET_DATE_TIME
ISO_ZONED_DATE_TIME
ISO_ORDINAL_DATE
ISO_WEEK_DATE
RFC_1123_DATE_TIME
We can use the following methods from DateTimeFormatter
class
to format a date time value.
String format(TemporalAccessor temporal) void formatTo(TemporalAccessor temporal, Appendable appendable)
The following code shows how to use ISO_DATE formatter to format a LocalDate, an OffsetDateTime, and ZonedDateTime.
import java.time.LocalDate; import java.time.OffsetDateTime; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; //from ww w .ja v a 2s .c om public class Main{ public static void main(String[] argv){ String ldStr = DateTimeFormatter.ISO_DATE.format(LocalDate.now()); System.out.println(ldStr); String odtStr = DateTimeFormatter.ISO_DATE.format(OffsetDateTime.now()); System.out.println(odtStr); String zdtStr = DateTimeFormatter.ISO_DATE.format(ZonedDateTime.now()); System.out.println(zdtStr); } }
The code above generates the following result.
We can also format a date time object using the the format() from the date time classes.
import java.time.LocalDate; import java.time.OffsetDateTime; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; //from ww w . j a v a 2s. c o m public class Main { public static void main(String[] argv) { LocalDate ld = LocalDate.now(); String ldStr = ld.format(DateTimeFormatter.ISO_DATE); System.out.println("Local Date: " + ldStr); OffsetDateTime odt = OffsetDateTime.now(); String odtStr = odt.format(DateTimeFormatter.ISO_DATE); System.out.println("Offset Datetime: " + odtStr); ZonedDateTime zdt = ZonedDateTime.now(); String zdtStr = zdt.format(DateTimeFormatter.ISO_DATE); System.out.println("Zoned Datetime: " + zdtStr); } }
The code above generates the following result.