首页 > 编程语言 >java日期格式化

java日期格式化

时间:2024-07-12 20:42:55浏览次数:10  
标签:格式化 System println 日期 printFormatDate date java null out

java日期格式化

1.一代日期类Date结合SimpleDateFormat格式化(不推荐)

/**
 * @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

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

第二代日期类:java.util.Calendar

  1. 可变性
    • Date类类似,Calendar对象也是可变的。这同样可能导致在多线程环境下的数据不一致问题。
  2. 偏移性
    • 尽管Calendar类在年份和月份的表示上比Date类更加直观(年份从当前年份开始计算,月份从1开始编号),但它仍然保留了某些偏移性,比如星期字段的编号是从周日开始的(即周日为1,周六为7)。
  3. 格式化
    • Calendar类本身不提供直接的格式化方法。如果需要格式化日期,通常需要与SimpleDateFormat类结合使用,这增加了使用的复杂性。
  4. 线程安全性
    • Calendar类同样不是线程安全的。在多线程环境中,如果多个线程同时访问或修改同一个Calendar对象,可能会导致数据不一致的问题。
  5. 设计复杂性
    • Calendar类的设计相对复杂,它包含了多个字段(如年、月、日、时、分、秒等),并且这些字段之间存在一定的依赖关系。这增加了使用的难度和出错的可能性。

综上所述,前面两代日期类在可变性、偏移性、格式化、线程安全性以及设计复杂性等方面都存在一些不足之处。为了克服这些不足,Java在JDK 8中引入了新的日期时间API,包括LocalDateLocalTimeLocalDateTime等类,以及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区

配置全局日期转换类

  1. 注意:JavaBean中的属性上面标注的 @JsonFormat、@DateTimeFormat、@Temporal的注解优先级高于配置类GlobalDateConvertConfig.java
  2. 配置全局日期格式化,支持Date、LocalDate、LocalDateTime、LocalTime等类型的格式化
  3. 编写一个配置类并实现WebMvcConfigurer接口,重写extendMessageConverters(List> converters)方法来实现
  4. 配置类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

标签:格式化,System,println,日期,printFormatDate,date,java,null,out
From: https://www.cnblogs.com/shui-notes/p/18299353

相关文章

  • 计算机Java项目|基于SpringBoot的学生选课系统的设计与实现
    作者主页:编程指南针作者简介:Java领域优质创作者、CSDN博客专家、CSDN内容合伙人、掘金特邀作者、阿里云博客专家、51CTO特邀作者、多年架构师设计经验、腾讯课堂常驻讲师主要内容:Java项目、Python项目、前端项目、人工智能与大数据、简历模板、学习资料、面试题库、技术互......
  • 计算机Java项目|基于SpringBoot的企业人事管理系统
    作者主页:编程指南针作者简介:Java领域优质创作者、CSDN博客专家、CSDN内容合伙人、掘金特邀作者、阿里云博客专家、51CTO特邀作者、多年架构师设计经验、腾讯课堂常驻讲师主要内容:Java项目、Python项目、前端项目、人工智能与大数据、简历模板、学习资料、面试题库、技术互......
  • 动态条件实现java
    提交页面设计 json数据格式[{"name":"规则1","action":{"with":[{"type":"SHOW","targets":[......
  • Java三剑客:封装、继承、多态的魔法世界
    第一章:封装的艺术——保护你的宝藏案例分析:银行账户系统想象一下,你正在构建一个银行账户系统。每个账户都有一个余额,这个余额需要受到严格的保护,不能被随意修改。我们可以通过封装来实现这一目标。示例代码:publicclassBankAccount{privatedoublebalance;//......
  • JAVA利用HttpClient进行POST请求(HTTPS)
    finalHttpClientUtilhttpClientUtil=newHttpClientUtil();finalMap<String,String>map=Maps.newHashMap();map.put("username",workNo);map.put("password",passwd);finalStringresultStr......
  • java将小写金额转换为大写的工具类
    摘自:http://www.cnblogs.com/niuyaoBolg/p/5654113.htmlpublicclassTool{privatestaticfinalStringUNIT="万千佰拾亿千佰拾万千佰拾元角分";privatestaticfinalStringDIGIT="零壹贰叁肆伍陆柒捌玖";privatestaticfinaldoub......
  • mysql获取按日期排序获取最新的记录
    今天让一个数据查询难了。主要是对groupby理解的不够深入。才出现这样的情况这种需求,我想很多人都遇到过。下面是我模拟我的内容表我现在需要取出每个分类中最新的内容select*fromtestgroupbycategory_idorderby`date`结果如下:明显。这不是我想要的数据,原因是msyql......
  • 【JavaWeb程序设计】EL和JSTL
    目录一、在数据库Book中建立表Tbook,包含图书ID,图书名称,图书价格。实现模糊查询图书,如果图书的价格在50元以上,则以黄色字体显示书名。相应的模糊查询放在Servlet中实现,在图书的显示代码中使用JSTL。1.运行截图2.建表(tbook)并插入数据3.search.jsp(1)查找表单(2)CSS4.mybat......
  • JavaScript调试技巧总结
    debug javascript最全面的JavaScript调试技巧总结本文将一一讲解各种前端JS调试技巧,也许你已经熟练掌握,那让我们一起来温习,也许有你没见过的方法,不妨一起来学习,也许你尚不知如何调试,赶紧趁此机会填补空白。Thisentrywaspostedin Review andtagged debug, javasc......
  • 格式化金额 使其保留2位小数(千分位符号)
    1//格式化金额使其保留2位小数2functionformateAmount(val){3/*4*参数说明:5*number:要格式化的数字6*decimals:保留几位小数7*dec_point:小数点符号8*thousands_sep:千分位符号9**/10varnumber=val;......