Android 使用DateFormat格式化时间

2,632 阅读2分钟

这是我参与 8 月更文挑战的第 7 天,活动详情查看: 8月更文挑战

背景

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

DateFormat

DateFormat在三个包中都有这个类,分别是Java.text包,android.text.format包和android.icu.text包,由于android.icu.text包下的DateFormat类目前没用过,所以本章暂时不涉及, 主要写Java.textandroid.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));

效果 image.png

格式化日期+时间

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));

image.png

android.text.DateFormat

从代码上看,android.text.DateFormat大体上是java.text.DateFormat类的一个封装和扩展

常见方法

format(CharSequence inFormat, Date inDate)系列方法,用法和SimpleDateFormat中的format方法一致,但是官方文档不建议提供自己的格式字符串
getDateFormat:返回一个 DateFormat 对象,该对象可以根据上下文的区域设置以短格式格式化日期
getLongDateFormat:返回一个 DateFormat 对象,该对象可以为上下文的区域设置以长格式(例如,2000 年 1 月 3 日,星期一)格式化日期。
getMediumDateFormat返回一个 DateFormat 对象,该对象可以为上下文的区域设置以中等形式(例如 2000 年 1 月 3 日)格式化日期。
getTimeFormat返回一个 DateFormat 对象,该对象可以根据上下文的区域设置和用户的 12 小时制/24 小时制首选项设置时间格式。
is24HourFormat如果时间应该被格式化为 24 小时时间,则返回 true,如果时间应该被格式化为 12 小时 (AM/PM) 时间,则返回 false。