当前位置:  首页>> 技术小册>> Java语言基础9-常用API和常见算法

  • 在 JDK8 中,使用 DateTimeFormat 类进行日期时间的格式化。
  • 获取 DateTimeFormat :
  1. public static DateTimeFormatter ofPattern(String pattern) {}
  • 格式化:
  1. public String format(TemporalAccessor temporal) {}
  • 解析:
  1. public TemporalAccessor parse(CharSequence text) {}
  • 示例:
  1. package com.github.date.jdk8.demo14;
  2. import java.time.LocalDateTime;
  3. import java.time.format.DateTimeFormatter;
  4. import java.time.temporal.TemporalAccessor;
  5. /**
  6. * @author maxiaoke.com
  7. * @version 1.0
  8. */
  9. public class Test {
  10. public static void main(String[] args) {
  11. DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
  12. String format = df.format(LocalDateTime.now());
  13. System.out.println("format = " + format); // format = 2021-09-27 13:55:51
  14. TemporalAccessor parse = df.parse("2011-11-11 11:11:11");
  15. LocalDateTime from = LocalDateTime.from(parse);
  16. System.out.println("from = " + from); // from = 2011-11-11T11:11:11
  17. }
  18. }

该分类下的相关小册推荐: