相关文章推荐
道上混的饭盒  ·  Get-Date ...·  2 月前    · 
冷静的热带鱼  ·  【jdk1.8】LocalDateTime ...·  2 月前    · 
讲道义的高山  ·  Phi和psi_百度知道·  2 年前    · 
没读研的小蝌蚪  ·  Spark ...·  2 年前    · 
小眼睛的牙膏  ·  ToggleButton Class ...·  2 年前    · 
内向的冲锋衣  ·  大数据开发之Spark ...·  3 年前    · 
* @author shui * @description 一代日期类Date结合SimpleDateFormat格式化(SimpleDateFormat只能格式化Date类型) * @created 2024/7/11 public class SimpleDateFormatExample { public static void main(String[] args) { Date date; // date = new Date(); // 当前日期时间 date = new Date(124, 0, 2, 13, 4, 5); // 测试日期时间, 此方法是在1900+输入的年份,具体看源码 System.out.println(new SimpleDateFormat("yy年MM月dd日").format(date)); System.out.println(new SimpleDateFormat("yyyy年MM月dd日").format(date)); System.out.println(new SimpleDateFormat("HH时mm分").format(date)); System.out.println(new SimpleDateFormat("yyyy/MM/dd日 HH:mm:ss").format(date)); System.out.println(new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒 E").format(date)); System.out.println(new SimpleDateFormat("yyyy-MM-dd HH-mm-ss").format(date)); System.out.println(new SimpleDateFormat("今年已经过了DDD天,快w个星期,现在是这个月的第W个星期").format(date)); // y 年,一个y代表一位 "yyy"代表019,"yyyy"代表2019 // M 月份 例如八月,M代表8,MM代表08 // w 一年中的第几周 常用ww表示 // W 一个月中的第几周 常用WW表示 // d 一个月中的第几天 常用dd表示 // D 一年中的第几天 常用DDD表示 // E 星期几,用E表示星期,根据不同语言环境返回 CHINA表示星期几,US表示英文缩写 // a 上午或下午 am代表上午,pm代表下午 // H 一天中的小时数,二十四小时制 常用HH表示 // h 一天中的小时数,十二小时制 常用hh表示 // m 分钟数 常用mm表示 // s 秒数 常用ss表示 // S 毫秒数 常用SSS表示

2.二代日期类Calendar格式化

* @author shui * @description 二代日期类Calendar格式化 * @created 2024/7/11 public class CalendarExample { public static void main(String[] args) { //1.Calendar是一个抽象类,并且构造器的private //2.可以通过 getInstance()来获取实例 //3.通过来大量的方法和字段提供给程序员(灵活) //4.如果我们需要按照 24小时进制来获取时间,Calendar.HOUR 改成->Calendar.HOUR_OF_DAY Calendar c = Calendar.getInstance();//创建日历类对象 System.out.println("c=" + c); //2.获取日历对象的某个日历字段 System.out.println("年:" + c.get(Calendar.YEAR)); //这里为什么要+1,因为Calendar 返回月的时候,是从0开始编号 System.out.println("月:" + (c.get(Calendar.MONTH)+1)); System.out.println("日:" + c.get(Calendar.DAY_OF_MONTH)); System.out.println("小时:" + c.get(Calendar.HOUR)); System.out.println("分钟:" + c.get(Calendar.MINUTE)); System.out.println("秒:" + c.get(Calendar.SECOND)); //Calendar 没有专门的格式化方式,使用需要程序员直接来组合显示 System.out.println(c.get(Calendar.YEAR) + "-" + (c.get(Calendar.MONTH)+1) + "-" + c.get(Calendar.DAY_OF_MONTH) + " " + c.get(Calendar.HOUR) + ":" + c.get(Calendar.MINUTE) + ":" + c.get(Calendar.SECOND));

3.前面两代日期类的不足分析

前面两代日期类,即Java中的 java.util.Date 类和 java.util.Calendar 类,各自存在一些不足之处。以下是对这两类日期类不足之处的详细分析:

第一代日期类: java.util.Date

  • Date 对象是可变的,这意味着一旦创建了 Date 对象,就可以修改它表示的时间。然而,像日期和时间这样的类应该是不可变的,以避免在多线程环境下引发问题。
  • Date 类中的年份是从1900年开始计算的,而月份则是从0开始编号的(即0代表1月,11代表12月)。这种偏移性可能导致在使用时产生混淆。
  • 尽管 Date 类提供了 toString() 方法来将日期转换为字符串,但它提供的格式通常是固定的,并且不够灵活。如果需要自定义日期格式,通常需要使用 SimpleDateFormat 类进行格式化,但这增加了使用的复杂性。
  • 线程安全性
  • Date 类不是线程安全的,这意味着在多线程环境中,如果多个线程同时修改同一个 Date 对象,可能会导致数据不一致的问题。
  • 随着 Calendar 类的引入, Date 类中的许多方法逐渐被弃用,因为它们的功能被 Calendar 类更好地实现或替代了。
  • 第二代日期类: java.util.Calendar

  • Date 类类似, Calendar 对象也是可变的。这同样可能导致在多线程环境下的数据不一致问题。
  • 尽管 Calendar 类在年份和月份的表示上比 Date 类更加直观(年份从当前年份开始计算,月份从1开始编号),但它仍然保留了某些偏移性,比如星期字段的编号是从周日开始的(即周日为1,周六为7)。
  • Calendar 类本身不提供直接的格式化方法。如果需要格式化日期,通常需要与 SimpleDateFormat 类结合使用,这增加了使用的复杂性。
  • 线程安全性
  • Calendar 类同样不是线程安全的。在多线程环境中,如果多个线程同时访问或修改同一个 Calendar 对象,可能会导致数据不一致的问题。
  • 设计复杂性
  • Calendar 类的设计相对复杂,它包含了多个字段(如年、月、日、时、分、秒等),并且这些字段之间存在一定的依赖关系。这增加了使用的难度和出错的可能性。
  • 综上所述,前面两代日期类在可变性、偏移性、格式化、线程安全性以及设计复杂性等方面都存在一些不足之处。为了克服这些不足,Java在JDK 8中引入了新的日期时间API,包括 LocalDate LocalTime LocalDateTime 等类,以及 DateTimeFormatter 用于格式化日期和 Instant 用于表示时间戳等,这些新的类和方法提供了更加强大和灵活的日期时间处理能力。

    4.使用String.format()格式化

    在java中String类格式化的方法,是静态format()用于创建格式化的字符串。

    format(String format, Object... args) 新字符串使用本地语言环境,返回格式化后的新字符串。

    format(Locale locale, String format, Object... args) 使用指定语言环境,返回格式化后的新字符串。

    格式化一代日期类

    * @author shui * @description String.format()格式化一代日期类Date * @created 2024/7/10 public class StringFormatDateExample { public static void main(String[] args) { Date date; // date = new Date(); // 当前日期时间 date = new Date(124, 0, 2, 13, 4, 5); // 测试日期时间, 此方法是在1900+输入的年份,具体看源码 System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date)); // 2024-01-02 03:04:05 // %tx 表示日期格式 System.out.println("主要测试本地语言环境"); System.out.println("===============================================日期格式化==============================================="); printFormatDate(date, "%te", "一个月中的某一天(1~31)(不保留高位0)", null); // 2 printFormatDate(date, "%td", "一个月中的第几天(1~31)(保留高位0)", null); // 02 printFormatDate(date, "%tj", "一年中的第几天(1~366)(保留高位0)", null); // 002 printFormatDate(date, "%tY", "4位年份", null); // 2024 printFormatDate(date, "%ty", "2位年份", null); // 24 printFormatDate(date, "%tm", "月份", null); // 01 printFormatDate(date, "%tb", "指定语言环境的月份简称", null); // 一月 printFormatDate(date, "%tB", "指定语言环境的月份全称", null); // 一月 printFormatDate(date, "%ta", "指定语言环境的星期简称", null); // 星期二 printFormatDate(date, "%tA", "指定语言环境的星期全称", null); // 星期二 System.out.println("指定美国语言环境"); printFormatDate(date, "%tb", "指定语言环境的月份简称", Locale.US); // Jan printFormatDate(date, "%tB", "指定语言环境的月份全称", Locale.US); // January printFormatDate(date, "%ta", "指定语言环境的星期简称", Locale.US); // Tue printFormatDate(date, "%tA", "指定语言环境的星期全称", Locale.US); // Tuesday System.out.println("===============================================时间格式化==============================================="); printFormatDate(date, "%tH", "2位数字的24时制的小时(00~23)", null); // 03 printFormatDate(date, "%tI", "2位数字的12时制的小时(00~23)", null); // 03 printFormatDate(date, "%tM", "2位数字的分钟(00~59)", null); // 04 printFormatDate(date, "%tS", "2位数字的秒数(00~60)", null); // 05 printFormatDate(date, "%tL", "3位数字的毫秒(000~999)", null); // 000 printFormatDate(date, "%tp", "指定语言环境下的上午或下午标记", null); // 上午 printFormatDate(date, "%tZ", "时区缩写形式的字符串", null); // CST System.out.println("===============================================日期和时间组合格式化==============================================="); printFormatDate(date, "%tF", "年-月-日格式", null); // 2024-01-02 printFormatDate(date, "%tD", "月/日/年格式", null); // 01/02/24 printFormatDate(date, "%tT", "时:分:秒24时制", null); // 03:04:05 printFormatDate(date, "%tR", "时:分 24时制", null); // 03:04 printFormatDate(date, "%tc", "星期 月 日 时:分:秒 时区缩写 年 24小时制", null); // 星期二 一月 02 03:04:05 CST 2024 printFormatDate(date, "%tr", "时:分 上/下午 12时制", null); // 03:04:05 上午 System.out.println("===============================================自由组合格式化==============================================="); System.out.println(String.format("%tF %tT", date, date)); // 2024-01-02 13:04:05 System.out.println(String.format("%tY年%tm月%td日 %tH时%tM分%tS秒", date, date, date, date, date, date)); // 2024年01月02日 13时04分05秒 // 省略写法,可以不用String,format, 但必需用 printf , 末尾用 %n 实现换行 System.out.printf("%tF %tT%n", date, date); // 2024-01-02 13:04:05 System.out.printf("%tY年%tm月%td日 %tH时%tM分%tS秒%n", date, date, date, date, date, date); // 2024年01月02日 13时04分05秒 public static void printFormatDate(Date date, String formatStr, String message, Locale l) { if (l == null) { l = Locale.getDefault(); System.out.println(processStr(formatStr, 12) + "\t" + processStr(String.format(l, formatStr, date), 36) + "\t" + processStr(message, 36)); public static String processStr(String str, int len) { if (str.length() >= len) { return str; } else { StringBuilder sb = new StringBuilder(); sb.append(str); for (int i = 0; i < len - str.length(); i++) { sb.append(" "); return sb.toString();

    格式化二代日期类

    * @author shui * @description String.format()格式化二代日期类Calendar * @created 2024/7/11 public class StringFormatCalendarExample { public static void main(String[] args) { Calendar date = Calendar.getInstance(); // %tx 表示日期格式 System.out.println("主要测试本地语言环境"); System.out.println("===============================================日期格式化==============================================="); printFormatDate(date, "%te", "一个月中的某一天(1~31)(不保留高位0)", null); // 2 printFormatDate(date, "%td", "一个月中的第几天(1~31)(保留高位0)", null); // 02 printFormatDate(date, "%tj", "一年中的第几天(1~366)(保留高位0)", null); // 002 printFormatDate(date, "%tY", "4位年份", null); // 2024 printFormatDate(date, "%ty", "2位年份", null); // 24 printFormatDate(date, "%tm", "月份", null); // 01 printFormatDate(date, "%tb", "指定语言环境的月份简称", null); // 一月 printFormatDate(date, "%tB", "指定语言环境的月份全称", null); // 一月 printFormatDate(date, "%ta", "指定语言环境的星期简称", null); // 星期二 printFormatDate(date, "%tA", "指定语言环境的星期全称", null); // 星期二 System.out.println("指定美国语言环境"); printFormatDate(date, "%tb", "指定语言环境的月份简称", Locale.US); // Jan printFormatDate(date, "%tB", "指定语言环境的月份全称", Locale.US); // January printFormatDate(date, "%ta", "指定语言环境的星期简称", Locale.US); // Tue printFormatDate(date, "%tA", "指定语言环境的星期全称", Locale.US); // Tuesday System.out.println("===============================================时间格式化==============================================="); printFormatDate(date, "%tH", "2位数字的24时制的小时(00~23)", null); // 03 printFormatDate(date, "%tI", "2位数字的12时制的小时(00~23)", null); // 03 printFormatDate(date, "%tM", "2位数字的分钟(00~59)", null); // 04 printFormatDate(date, "%tS", "2位数字的秒数(00~60)", null); // 05 printFormatDate(date, "%tL", "3位数字的毫秒(000~999)", null); // 000 printFormatDate(date, "%tp", "指定语言环境下的上午或下午标记", null); // 上午 printFormatDate(date, "%tZ", "时区缩写形式的字符串", null); // CST System.out.println("===============================================日期和时间组合格式化==============================================="); printFormatDate(date, "%tF", "年-月-日格式", null); // 2024-01-02 printFormatDate(date, "%tD", "月/日/年格式", null); // 01/02/24 printFormatDate(date, "%tT", "时:分:秒24时制", null); // 03:04:05 printFormatDate(date, "%tR", "时:分 24时制", null); // 03:04 printFormatDate(date, "%tc", "星期 月 日 时:分:秒 时区缩写 年 24小时制", null); // 星期二 一月 02 03:04:05 CST 2024 printFormatDate(date, "%tr", "时:分 上/下午 12时制", null); // 03:04:05 上午 System.out.println("===============================================自由组合格式化==============================================="); System.out.println(String.format("%tF %tT", date, date)); // 2024-01-02 13:04:05 System.out.println(String.format("%tY年%tm月%td日 %tH时%tM分%tS秒", date, date, date, date, date, date)); // 2024年01月02日 13时04分05秒 // 省略写法,可以不用String,format, 但必需用 printf , 末尾用 %n 实现换行 System.out.printf("%tF %tT%n", date, date); // 2024-01-02 13:04:05 System.out.printf("%tY年%tm月%td日 %tH时%tM分%tS秒%n", date, date, date, date, date, date); // 2024年01月02日 13时04分05秒 public static void printFormatDate(Calendar date, String formatStr, String message, Locale l) { if (l == null) { l = Locale.getDefault(); System.out.println(processStr(formatStr, 12) + "\t" + processStr(String.format(l, formatStr, date), 36) + "\t" + processStr(message, 36)); public static String processStr(String str, int len) { if (str.length() >= len) { return str; } else { StringBuilder sb = new StringBuilder(); sb.append(str); for (int i = 0; i < len - str.length(); i++) { sb.append(" "); return sb.toString();

    格式化三代日期类

    * @author shui * @description String.format()格式化二代日期类LocalDateTime * @created 2024/7/11 public class StringFormatLocalDateTimeExample { public static void main(String[] args) { LocalDateTime date = LocalDateTime.now(); // %tx 表示日期格式 System.out.println("主要测试本地语言环境"); System.out.println("===============================================日期格式化==============================================="); printFormatDate(date, "%te", "一个月中的某一天(1~31)(不保留高位0)", null); // 2 printFormatDate(date, "%td", "一个月中的第几天(1~31)(保留高位0)", null); // 02 printFormatDate(date, "%tj", "一年中的第几天(1~366)(保留高位0)", null); // 002 printFormatDate(date, "%tY", "4位年份", null); // 2024 printFormatDate(date, "%ty", "2位年份", null); // 24 printFormatDate(date, "%tm", "月份", null); // 01 printFormatDate(date, "%tb", "指定语言环境的月份简称", null); // 一月 printFormatDate(date, "%tB", "指定语言环境的月份全称", null); // 一月 printFormatDate(date, "%ta", "指定语言环境的星期简称", null); // 星期二 printFormatDate(date, "%tA", "指定语言环境的星期全称", null); // 星期二 System.out.println("指定美国语言环境"); printFormatDate(date, "%tb", "指定语言环境的月份简称", Locale.US); // Jan printFormatDate(date, "%tB", "指定语言环境的月份全称", Locale.US); // January printFormatDate(date, "%ta", "指定语言环境的星期简称", Locale.US); // Tue printFormatDate(date, "%tA", "指定语言环境的星期全称", Locale.US); // Tuesday System.out.println("===============================================时间格式化==============================================="); printFormatDate(date, "%tH", "2位数字的24时制的小时(00~23)", null); // 03 printFormatDate(date, "%tI", "2位数字的12时制的小时(00~23)", null); // 03 printFormatDate(date, "%tM", "2位数字的分钟(00~59)", null); // 04 printFormatDate(date, "%tS", "2位数字的秒数(00~60)", null); // 05 printFormatDate(date, "%tL", "3位数字的毫秒(000~999)", null); // 000 printFormatDate(date, "%tp", "指定语言环境下的上午或下午标记", null); // 上午 // printFormatDate(date, "%tZ", "时区缩写形式的字符串", null); // 报异常 System.out.println("===============================================日期和时间组合格式化==============================================="); printFormatDate(date, "%tF", "年-月-日格式", null); // 2024-01-02 printFormatDate(date, "%tD", "月/日/年格式", null); // 01/02/24 printFormatDate(date, "%tT", "时:分:秒24时制", null); // 03:04:05 printFormatDate(date, "%tR", "时:分 24时制", null); // 03:04 // printFormatDate(date, "%tc", "星期 月 日 时:分:秒 时区缩写 年 24小时制", null); // 异常 printFormatDate(date, "%tr", "时:分 上/下午 12时制", null); // 03:04:05 上午 System.out.println("===============================================自由组合格式化==============================================="); System.out.println(String.format("%tF %tT", date, date)); // 2024-01-02 13:04:05 System.out.println(String.format("%tY年%tm月%td日 %tH时%tM分%tS秒", date, date, date, date, date, date)); // 2024年01月02日 13时04分05秒 // 省略写法,可以不用String,format, 但必需用 printf , 末尾用 %n 实现换行 System.out.printf("%tF %tT%n", date, date); // 2024-01-02 13:04:05 System.out.printf("%tY年%tm月%td日 %tH时%tM分%tS秒%n", date, date, date, date, date, date); // 2024年01月02日 13时04分05秒 // LocalDate 和 LocalTime 自行测试 public static void printFormatDate(LocalDateTime date, String formatStr, String message, Locale l) { if (l == null) { l = Locale.getDefault(); System.out.println(processStr(formatStr, 12) + "\t" + processStr(String.format(l, formatStr, date), 36) + "\t" + processStr(message, 36)); public static String processStr(String str, int len) { if (str.length() >= len) { return str; } else { StringBuilder sb = new StringBuilder(); sb.append(str); for (int i = 0; i < len - str.length(); i++) { sb.append(" "); return sb.toString();

    5.三代日期类LocalDateTime结合DateTimeFormatter格式化 (推荐)

    * @author shui * @description 三代日期类LocalDateTime结合DateTimeFormatter格式化(DateTimeFormatter只能格式化LocalDateTime/LocalDate/LocalTime/ZonedDateTime类型) * @created 2024/7/12 public class DateTimeFormatterExample { public static void main(String[] args) { //第三代日期 //1.使用now() 返回表示当前时间日期的 对象 LocalDateTime now = LocalDateTime.now(); // LocalDate now = LocalDate.now(); // LocalTime now = LocalTime.now(); // ZonedDateTime now = ZonedDateTime.now(); System.out.println(now); //2.使用DateTimeFormatter 对象来进行格式化 // 创建 DateTimeFormatter对象 DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH小时mm分钟ss秒"); System.out.println(processStr("now", 12) + "\t\t=\t\t" + dateTimeFormatter.format(now)); System.out.println(processStr("年", 12) + "\t\t=\t\t" + now.getYear()); System.out.println(processStr("月", 12) + "\t\t=\t\t" + now.getMonth()); System.out.println(processStr("月", 12) + "\t\t=\t\t" + now.getMonthValue()); System.out.println(processStr("日", 12) + "\t\t=\t\t" + now.getDayOfMonth()); System.out.println(processStr("时", 12) + "\t\t=\t\t" + now.getHour()); System.out.println(processStr("分", 12) + "\t\t=\t\t" + now.getMinute()); System.out.println(processStr("秒", 12) + "\t\t=\t\t" + now.getSecond()); LocalDate now1 = LocalDate.now();//可以获取年月日 System.out.println(processStr("now1", 12) + "\t\t=\t\t" + now1); LocalTime now2 = LocalTime.now();//获取时分秒 System.out.println(processStr("now2", 12) + "\t\t=\t\t" + now2); //通过 plus 和 minus 方法可以对当前时间进行加或者减 //2月后 System.out.println(processStr("890天", 12) + "\t\t=\t\t" + dateTimeFormatter.format(now.minusMonths(2))); System.out.println(processStr("now", 12) + "\t\t=\t\t" + dateTimeFormatter.format(now)); //890天后 System.out.println(processStr("890天后", 12) + "\t\t=\t\t" + dateTimeFormatter.format(now.plusDays(890))); System.out.println(processStr("now", 12) + "\t\t=\t\t" + dateTimeFormatter.format(now)); //3456分钟前 System.out.println(processStr("3456分钟前", 12) + "\t\t=\t\t" + dateTimeFormatter.format(now.minusMinutes(3456))); System.out.println(processStr("now", 12) + "\t\t=\t\t" + dateTimeFormatter.format(now)); public static String processStr(String str, int len) { if (str.length() >= len) { return str; } else { StringBuilder sb = new StringBuilder(); sb.append(str); for (int i = 0; i < len - str.length(); i++) { sb.append(" "); return sb.toString();

    6.springmvc日期格式化(前端传输表单格式数据)

    1.在实体中加入日期格式化注解

    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date createTime;
    

    2.在单个controller中设置表单日期,把Date.class格式化(会将该控制器所有请求参数Date类型都按指定格式化)

    7.springboot日期格式化(json数据)

    1.全局时间格式化

    Spring Boot 默认使用 Jackson 作为 JSON 处理库,所以设置会生效(一般用配置文件配置即可)

    application.yaml文件

    # 格式化全局时间字段
    spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
    # 指定时间区域类型
    spring.jackson.time-zone=GMT+8
    

    application.properties文件

    spring.jackson.date-format=yyyy-MM-dd HH:mm:ss	#统一转换为指定格式
    spring.jackson.time-zone=GMT+8	# 时区修改为东8区
    

    配置全局日期转换类

  • 注意:JavaBean中的属性上面标注的 @JsonFormat、@DateTimeFormat、@Temporal的注解优先级高于配置类GlobalDateConvertConfig.java
  • 配置全局日期格式化,支持Date、LocalDate、LocalDateTime、LocalTime等类型的格式化
  • 编写一个配置类并实现WebMvcConfigurer接口,重写extendMessageConverters(List> converters)方法来实现
  • 配置类GlobalDateConvertConfig.java如下
  • * 配置全局日期格式化,支持Date、LocalDate、LocalDateTime、LocalTime等类型的转换 * 使用此方法, 以下 spring-boot: jackson时间格式化 配置 将会失效 * spring.jackson.time-zone=GMT+8 * spring.jackson.date-format=yyyy-MM-dd HH:mm:ss * 原因: 会覆盖 @EnableAutoConfiguration 关于 WebMvcAutoConfiguration 的配置 @Configuration public class GlobalDateConvertConfig implements WebMvcConfigurer { @Override public void extendMessageConverters(List<HttpMessageConverter<?>> converters) { //WebMvcConfigurer.super.extendMessageConverters(converters); MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); ObjectMapper objectMapper = converter.getObjectMapper(); SimpleModule simpleModule = new SimpleModule(); // LocalDateTime时间格式化 simpleModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))); // LocalDate时间格式化 simpleModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd"))); // LocalTime时间格式化 simpleModule.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern("HH:mm:ss"))); objectMapper.registerModule(simpleModule); //Data 时间格式化 objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")); converter.setObjectMapper(objectMapper); converters.add(0, converter);

    2.在实体中加注解

    // Jackson设置日期格式
    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", timezone="GMT+8")
    private Date createTime;
    // Fastjson 设置日期格式 
    @JSONField(format = "yyyy-MM-dd HH:mm:ss", timeZone = "UTC")
    private Date date;
    // 注解将yyyy-MM-dd的形式转换为Date数据
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date birthday;
    @Temporal(TemporalType.TIMESTAMP)
    private Date createTime;
    // 说明
    // @JsonFormat注解适用于Jackson,@JSONField注解适用于Fastjson
    // @DateTimeFormat将字符类型转换为date类型(一般前后端不分离,表单提交数据使用)
    // @Temporal实现日期格式转换,它自带属性参数
    

    注意:需要日期工具类,直接用Hu-tool的即可,

    [中文文档]: https://doc.hutool.cn/ 文档

    <dependency>
        <groupId>cn.hutool</groupId>
        <artifactId>hutool-core</artifactId>
        <version>5.8.28</version>
    </dependency>
    

    8.部分前台格式化日期

    JSP模版引擎

     <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>   
        <fmt:formatDate value="${job.jobtime }" pattern="yyyy-MM-dd HH:mm:ss"/>  
    

    Freemarker模版引擎

    <input id="receiveAppTime" name="receiveAppTime" type="text" value="${(bean.receiveAppTime?string('yyyy-MM-dd'))!}" />  
    

    Thymeleaf模板引擎

    [[${#dates.format(date)}]] 或 th:text="${#dates.format(date)}
    [[${#dates.formatISO(date)}]] 或 th:text="${#dates.formatISO(date)}
    [[${#dates.format(date, 'yyyy-MM-dd HH:mm:ss')}]] 或 th:text="${#dates.format(date, 'yyyy-MM-dd HH:mm:ss')}
    

    JS格式化日期

    实现方法一(不灵活,需要重复编码)

    function formatDate(date) {  
      const year = date.getFullYear();  
      const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份是从0开始的  
      const day = String(date.getDate()).padStart(2, '0');  
      const hour = String(date.getHours()).padStart(2, '0');  
      const minute = String(date.getMinutes()).padStart(2, '0');  
      const second = String(date.getSeconds()).padStart(2, '0');  
      return `${year}-${month}-${day} ${hour}:${minute}:${second}`;  
    const date = new Date();  
    console.log(formatDate(date));
    

    实现方法二(工具类全局使用 ,灵活)

    function formatDate(date, options = {}) {  
        const year = date.getFullYear().toString();  
        const month = String(date.getMonth() + 1).padStart(2, '0');  
        const day = String(date.getDate()).padStart(2, '0');  
        const hour = options.hour24 ? String(date.getHours()).padStart(2, '0') :  
                                     ((h = date.getHours() % 12 || 12) < 10 ? '0' : '') + h;  
        const minute = String(date.getMinutes()).padStart(2, '0');  
        const second = String(date.getSeconds()).padStart(2, '0');  
        const ampm = options.hour24 ? '' : date.getHours() < 12 ? 'AM' : 'PM';  
        // 默认格式或自定义格式  
        const defaultFormat = `${year}-${month}-${day} ${hour}:${minute}:${second}`;  
        const customFormat = options.format || defaultFormat;  
        // 替换模板字符串中的占位符  
        return customFormat  
            .replace(/YYYY/g, year)  
            .replace(/MM/g, month)  
            .replace(/DD/g, day)  
            .replace(/HH/g, hour)  
            .replace(/mm/g, minute)  
            .replace(/ss/g, second)  
            .replace(/ampm/gi, ampm); // 注意大小写不敏感  
    // 使用示例  
    const now = new Date();  
    console.log(formatDate(now, { format: 'YYYY-MM-DD HH:mm:ss' })); // 标准24小时格式  
    console.log(formatDate(now, { format: 'MM/DD/YYYY hh:mm:ss ampm', hour24: false }));
    

    ElementUI的日期格式化

    <template>  
      <el-date-picker  
        v-model="value"  
        type="date"  
        placeholder="选择日期"  
        format="yyyy 年 MM 月 dd 日"  
        value-format="yyyy-MM-dd">  
      </el-date-picker>  
    </template>  
    <script>  
    export default {  
      data() {  
        return {  
          value: ''  
    </script>
    

    ElementPlus的日期格式化

    <el-date-picker
            v-model="value1"
            type="date"
            placeholder="选择日期"
            format="YYYY/MM/DD"
            value-format="YYYY-MM-DD"
    
    https://blog.csdn.net/WANGLI123956/article/details/131139869
    https://blog.csdn.net/gr912308719/article/details/80299898
    https://blog.csdn.net/pleaseprintf/article/details/131708101
    https://blog.csdn.net/m0_73709096/article/details/134101832
    https://www.cnblogs.com/luliang888/p/11075090.html
    https://www.cnblogs.com/woms/p/6037902.html
    https://blog.csdn.net/yuanjinshenglife/article/details/135901295
    https://blog.csdn.net/cxyxysam/article/details/135653224
    https://blog.csdn.net/qq_19309473/article/details/125041273
    https://blog.csdn.net/qq_45110186/article/details/136261827
    https://www.jb51.net/program/320962vro.htm
    https://cloud.tencent.com/developer/article/2044647
    https://cloud.tencent.com/developer/article/2044647