若要创建自定义DateTime格式器,请使用DateTimeFormatter。首先让我们看看时间-
DateTimeFormatter dtFormat = new DateTimeFormatterBuilder().appendValue(ChronoField.HOUR_OF_DAY) .appendLiteral(":") .appendValue(ChronoField.MINUTE_OF_HOUR) .appendLiteral(":") .appendValue(ChronoField.SECOND_OF_MINUTE) .toFormatter();
对于日期-
dtFormat = new DateTimeFormatterBuilder().appendValue(ChronoField.YEAR) .appendLiteral("/") .appendValue(ChronoField.MONTH_OF_YEAR) .appendLiteral("/") .appendValue(ChronoField.DAY_OF_MONTH) .toFormatter();
import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatterBuilder; import java.time.temporal.ChronoField; public class Demo { public static void main(String[] args) { DateTimeFormatter dtFormat = new DateTimeFormatterBuilder() .appendValue(ChronoField.HOUR_OF_DAY) .appendLiteral(":") .appendValue(ChronoField.MINUTE_OF_HOUR) .appendLiteral(":") .appendValue(ChronoField.SECOND_OF_MINUTE) .toFormatter(); System.out.println("Time = "+dtFormat.format(LocalDateTime.now())); dtFormat = new DateTimeFormatterBuilder() .appendValue(ChronoField.YEAR) .appendLiteral("/") .appendValue(ChronoField.MONTH_OF_YEAR) .appendLiteral("/") .appendValue(ChronoField.DAY_OF_MONTH) .toFormatter(); System.out.println("Date = "+dtFormat.format(LocalDateTime.now())); } }
输出结果
Time = 12:47:31 Date = 2019/4/19