Android 使用DateFormat格式化时间

背景

上篇文章使用了SimpleDateFormat进行格式化时间, 但是某些时候(比如根据语言或者时间对应不同的格式)并不足以适用于所有需求. 这篇文章主要介绍DateFormat的使用方法

DateFormat

DateFormat在三个包中都有这个类,分别是Java.text包,android.text.format包和android.icu.text包,由于android.icu.text包下的DateFormat类目前没用过,所以本章暂时不涉及, 主要写Java.text和android.text.format下的DateFormat类

java.text.DateFormat

主要方法getDateTimeInstance通过传入指定样式返回对应的格式字符串, 并自动根据语言转换

常用的样式常量
DateFormat.FULL 打印完整的日期时间
DateFormat.LONG 打印长样式的日期时间
DateFormat.MEDIUM 打印中等样式日期时间, 默认样式
DateFormat.SHORT 打印短样式的日期时间
DateFormat.DEFAULT 打印默认样式的日期时间
格式化日期
代码

Date date = new Date(System.currentTimeMillis());
System.out.print("DateFormat.FULL -- ");
System.out.println(DateFormat.getDateInstance(DateFormat.FULL).format(date));
System.out.print("DateFormat.LONG -- ");
System.out.println(DateFormat.getDateInstance(DateFormat.LONG).format(date));
System.out.print("DateFormat.MEDIUM -- ");
System.out.println(DateFormat.getDateInstance(DateFormat.MEDIUM).format(date));
System.out.print("DateFormat.SHORT -- ");
System.out.println(DateFormat.getDateInstance(DateFormat.SHORT).format(date));
System.out.print("DateFormat.DEFAULT -- ");
System.out.println(DateFormat.getDateInstance(DateFormat.DEFAULT).format(date));

效果

格式化日期+时间

Date date = new Date(System.currentTimeMillis());
System.out.print("DateFormat.FULL -- ");
System.out.println(DateFormat.getDateTimeInstance(DateFormat.FULL,DateFormat.FULL).format(date));
System.out.print("DateFormat.LONG -- ");
System.out.println(DateFormat.getDateTimeInstance(DateFormat.LONG,DateFormat.LONG).format(date));
System.out.print("DateFormat.MEDIUM -- ");
System.out.println(DateFormat.getDateTimeInstance(DateFormat.MEDIUM,DateFormat.MEDIUM).format(date));
System.out.print("DateFormat.SHORT -- ");
System.out.println(DateFormat.getDateTimeInstance(DateFormat.SHORT,DateFormat.SHORT).format(date));
System.out.print("DateFormat.DEFAULT -- ");
System.out.println(DateFormat.getDateTimeInstance(DateFormat.DEFAULT,DateFormat.DEFAULT).format(date));

作者:是芝麻吖
链接:https://juejin.cn/post/6993620457887006757
来源:稀土掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

posted @ 2022-09-14 22:35  yassine  阅读(1176)  评论(0编辑  收藏  举报