Java日期和时间格式器总结

Java日期和时间格式器总结,第1张

Java日期和时间格式器总结

文章目录
  • DateFormat
  • SimpleDateFormat
  • DateTimeFormatter

DateFormat

它是一个抽象类,提供了几个类方法用于获取DateFormat对象。

getDateInstance 返回一个日期格式器
getTimeInstance 返回一个时间格式器
getDateTimeInstance 返回一个日期、时间格式器

public static void main(String[] args) {

        Date date = new Date();
        DateFormat shortDateFormat = DateFormat.getDateInstance(DateFormat.SHORT);
        System.out.println("SHORT格式:" + shortDateFormat.format(date));

        DateFormat mediumDateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM);
        System.out.println("MEDIUM格式:" + mediumDateFormat.format(date));

        DateFormat longDateFormat = DateFormat.getDateInstance(DateFormat.LONG);
        System.out.println("LONG格式:" + longDateFormat.format(date));

        DateFormat shortTimeFormat = DateFormat.getTimeInstance(DateFormat.SHORT);
        System.out.println("SHORT格式:" + shortTimeFormat.format(date));

        DateFormat mediumTimeFormat = DateFormat.getTimeInstance(DateFormat.MEDIUM);
        System.out.println("MEDIUM格式:" + mediumTimeFormat.format(date));

        DateFormat longTimeFormat = DateFormat.getTimeInstance(DateFormat.LONG);
        System.out.println("LONG格式:" + longTimeFormat.format(date));

        DateFormat dateTimeFormat = DateFormat.getDateTimeInstance();
        System.out.println("DateTime格式:" + dateTimeFormat.format(date));


    }

输出:

SHORT格式:22-1-2
MEDIUM格式:2022-1-2
LONG格式:2022年1月2日
SHORT格式:上午8:25
MEDIUM格式:8:25:10
LONG格式:上午08时25分10秒
DateTime格式:2022-1-2 8:25:10

它有2个重要的抽象方法:
format:将日期转为String
parse:将String转为日期

它们的实现方法是在SimpleDateFormat类里。

SimpleDateFormat

是DateFormat的子类。可以非常灵活地格式化Date,也可以用于解析各种格式的日期字符串。

注意, 创建SimpleDateFormat对象时指定的pattern参数,pattern是一个使用日期字段占位符的日期模版。
具体有哪些占位符,可以看下该类的API,上面写的非常清楚:

特别要注意,同一个占位符,大小写的区别。例如,y 和 Y
y: year-of-era, 公元年
Y: week year,基于周来算年,(只要本周跨年,那么这周就算入下一年,即返回下一年)

public class SimpleDateFormatTest {
    public static void main(String[] args) {

        Calendar instance = Calendar.getInstance();
        instance.set(2019, 11, 31);
        Date date = instance.getTime();

        System.out.println(date);

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        System.out.println(simpleDateFormat.format(date));

        // 注意 y 和 Y的区别
        SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("YYYY-MM-dd");
        System.out.println(simpleDateFormat1.format(date));

    }
}

输出:

Tue Dec 31 08:47:47 CST 2019
2019-12-31
2020-12-31
DateTimeFormatter

从1.8新增。
获取DateTimeFormatter对象,有如下三种方式

  1. 直接使用静态常量创建DateTimeFormatter格式器
  2. 使用代表不同风格的枚举只FormatStyle来创建DateTimeFormatter格式器
  3. 根据模式字符串来创建DateTimeFormatter格式器。类似于SimpleDateFormat

注意,它的parse和format方法,都是和TemporalAccessor接口有关。
和我的上一篇博客里介绍的Java8 新增的日期、时间类有关

Java日期和时间类总结

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5695125.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存