格式化日期表示将日期/时间格式转换为预先定义的日期/时间格式。例如将日期“Fri May 18 15:46:24 CST2016” 格式转换为 “2016-5-18 15:46:24 星期五”的格式。
在 Java 中,可以使用 DateFormat 类和 SimpleDateFormat 类和String类来格式化日期,下面详细介绍这两个格式化日期类的使用。
DateFormat 类
DateFormat 是日期/时间格式化子类的抽象类,它以与语言无关的方式格式化并解析日期或时间。日期/时间格式化子类(如 SimpleDateFormat)允许进行格式化(也就是日期→文本)、解析(文本→日期)和标准化日期。
在创建 DateFormat 对象时不能使用 new 关键字,而应该使用 DateFormat 类中的静态方法 getDateInstance(),示例代码如下:
DateFormatdf=DateFormat.getDatelnstance();
在创建了一个 DateFormat 对象后,可以调用该对象中的方法来对日期/时间进行格式化。DateFormat 类中常用方法如表 1 所示。
表 1 DateFormat类的常用方法
方法
描述
String format(Date date)
将 Date 格式化日期/时间字符串
Calendar getCalendar()
获取与此日期/时间格式相关联的日历
static DateFormat getDateInstance()
获取具有默认格式化风格和默认语言环境的日期格式
static DateFormat getDateInstance(int style)
获取具有指定格式化风格和默认语言环境的日期格式
static DateFormat getDateInstance(int style,Locale locale)
获取具有指定格式化风格和指定语言环境的日期格式
static DateFormat getDateTimeInstance()
获取具有默认格式化风格和默认语言环境的日期/时间格式
static DateFormat getDateTimeInstance(intdateStyle,int timeStyle)
获取具有指定日期/时间格式化风格和默认语言环境的日期/时间格式
static DateFormat getDateTimeInstance(int dateStyle,int timeStyle,Locale locale)
获取具有指定日期/时间格式化风格和指定语言环境的日期/时间格式
static DateFormat getTimeInstance()
获取具有默认格式化风格和默认语言环境的时间格式
static DateFormat getTimeInstance(int style)
获取具有指定格式化风格和默认语言环境的时间格式
static DateFormat getTimeInstance(int style,Locale locale)
获取具有指定格式化风格和指定语言环境的时间格式
void setCalendar(Calendar newCalendar)
为此格式设置日历
Date parse(String source)
将给定的字符串解析成日期/时间
格式化样式主要通过 DateFormat 常量设置。将不同的常量传入到表 1 所示的方法中,以控制结果的长度。DateFormat 类的常量如下。
SHORT:完全为数字,如12.5.10或5:30pm。
MEDIUM:较长,如May10,2016。
LONG:更长,如May12,2016或11:15:32am。
FULL:是完全指定,如Tuesday、May10、2012AD或11:l5:42amCST。
使用 DateFormat 类格式化曰期/时间的示例如下:
// 获取不同格式化风格和中国环境的日期
DateFormatdf1=DateFormat.getDateInstance(DateFormat.SHORT,Locale.CHINA);
DateFormatdf2=DateFormat.getDateInstance(DateFormat.FULL,Locale.CHINA);
DateFormatdf3=DateFormat.getDateInstance(DateFormat.MEDIUM,Locale.CHINA);
DateFormatdf4=DateFormat.getDateInstance(DateFormat.LONG,Locale.CHINA);
// 获取不同格式化风格和中国环境的时间
DateFormatdf5=DateFormat.getTimeInstance(DateFormat.SHORT,Locale.CHINA);
DateFormatdf6=DateFormat.getTimeInstance(DateFormat.FULL,Locale.CHINA);
DateFormatdf7=DateFormat.getTimeInstance(DateFormat.MEDIUM,Locale.CHINA);
DateFormatdf8=DateFormat.getTimeInstance(DateFormat.LONG,Locale.CHINA);
// 将不同格式化风格的日期格式化为日期字符串
Stringdate1=df1.format(newDate());
Stringdate2=df2.format(newDate());
Stringdate3=df3.format(newDate());
Stringdate4=df4.format(newDate());
// 将不同格式化风格的时间格式化为时间字符串
Stringtime1=df5.format(newDate());
Stringtime2=df6.format(newDate());
Stringtime3=df7.format(newDate());
Stringtime4=df8.format(newDate());
// 输出日期
System.out.println("SHORT:"+date1+" "+time1);
System.out.println("FULL:"+date2+" "+time2);
System.out.println("MEDIUM:"+date3+" "+time3);
System.out.println("LONG:"+date4+" "+time4);
运行该段代码,输出的结果如下:
SHORT:18-10-15上午9:30
FULL:2018年10月15日星期一上午09时30分43秒CST
MEDIUM:2018-10-159:30:43
LONG:2018年10月15日上午09时30分43秒
该示例主要介绍了 DateFormat 类中方法与常量的结合使用,通过使用 DateFomat 类可以对日期进行不同风格的格式化。