首页 > 编程笔记 > Java笔记 阅读:19

Java中的DateFormat类(附带实例)

DateFormat 是对日期/时间进行格式化的抽象类,该类位于 java.text 包中。

DateFormat 类提供了很多方法,下表罗列了常用的方法:

方法名 功能
public Date parse(String source) 根据给定的字符串解析日期。
public final String format(Date date) 将日期格式化为字符串。
public static DateFormat getDateInstance() 获取一个日期的默认`DateFormat`实例。
public static DateFormat getDateInstance(int style) 获取一个日期的`DateFormat`实例,使用指定的日期风格。
public static DateFormat getDateInstance(Locale locale) 获取一个日期的`DateFormat`实例,使用指定的语言环境。
public static DateFormat getDateInstance(int style, Locale aLocale) 获取一个日期的`DateFormat`实例,使用指定的日期风格和语言环境。
public static DateFormat getDateTimeInstance() 获取一个日期和时间的默认`DateFormat`实例。
public static DateFormat getDateTimeInstance(int dateStyle, int timeStyle) 获取一个日期和时间的`DateFormat`实例,使用指定的日期和时间风格。
public static DateFormat getDateTimeInstance(int dateStyle, int timeStyle, Locale aLocale) 获取一个日期和时间的`DateFormat`实例,使用指定的日期和时间风格及语言环境。
public static DateFormat getTimeInstance() 获取一个时间的默认`DateFormat`实例。
public static DateFormat getTimeInstance(int style) 获取一个时间的`DateFormat`实例,使用指定的时间风格。
public static DateFormat getTimeInstance(int style, Locale aLocale) 获取一个时间的`DateFormat`实例,使用指定的时间风格和语言环境。
public void setLenient(boolean lenient) 设置解析日期字符串时是否为宽松模式。
public boolean isLenient() 返回解析日期字符串时是否为宽松模式。
public void setCalendar(Calendar newCalendar) 设置用于格式化和解析的日历。
public Calendar getCalendar() 返回用于格式化和解析的日历。
public void setTimeZone(TimeZone zone) 设置用于格式化和解析的时区。
public TimeZone getTimeZone() 返回用于格式化和解析的时区。

利用它们可以获得基于默认或者给定语言环境和多种格式化风格的默认日期/时间格式。格式包括 FULL、LONG、MEDIUM 和 SHORT。示例如下:
DateFormat.SHORT:11/4/2009
DateFormat.MEDIUM:Nov 4,2009
DateFormat.FULL: Wednesday ,November 4, 2009
DateFormat.LONG: Wednesday 4,2009

因为 DateFormat 是抽象类,所以实例化对象时不能用 new,而是通过工厂类方法返回 DateFormat 的实例。例如:
DateFormat df=DateFormat.getDateInstance();
DateFormat df=DateFormat.getDateInstance(DateFormat.SHORT);
DateFormat df=DateFormat.getDateInstance(DateFormat.SHORT, Locale.CHINA);

使用 DateFormat 类型可以在日期时间和字符串之间进行转换。例如,把字符串转换为一个 Date 对象,可以使用 DateFormat 的 parse() 方法,其代码片段如下所示:
DateFormat  df = DateFormate.getDateTimeInstance();
Date date=df.parse(“2011-05-28”);

还可以使用 DateFormat 的 format() 方法把一个 Date 对象转换为一个字符串,例如:
String  strDate=df.format(new Date());
另外,使用 getTimeInstance() 可获得该国的时间格式,使用 getDateTimeInstance() 可获得日期和时间格式。

相关文章