格式化时间
将时间转换为另外一种格式。例如,把 Long 类型的毫秒转换为 yyyy-MM-dd HH:mm:ss 格式。
private static DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(value), ZoneOffset.of("+8"));String date = df.format(localDateTime);
解析时间
将可支持的格式转换成Date、Long 等其他类型。yyyy-MM-dd HH:mm:ss 格式转换为毫秒。
private DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");Long date = LocalDateTime.parse(p.getText(), df).toInstant(ZoneOffset.of("+8")).toEpochMilli();
Date 转 String
LocalDateTime now = LocalDateTime.now();DateTimeFormatter pattern =DateTimeFormatter.ofPattern("G yyyy年MM月dd号 E a hh时mm分ss秒");String format = now.format(pattern);System.err.println(format);//公元 2019年05月18号 周六 上午 10时22分10秒
String 转 Date
DateTimeFormatter pattern =DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");//严格按照ISO yyyy-MM-dd验证,03写成3都不行LocalDateTime dt = LocalDateTime.parse("2017-12-03 10:15:30", pattern);System.err.println(dt.format(pattern));//2017-12-03 10:15:30
