SimpleDateFormat类的使用

来源:互联网 发布:儿童中文配音软件 编辑:程序博客网 时间:2024/06/07 06:44

DateFormat和SimpleDateFormat类都可以用来对时间和日期进行格式化以及反格式化,但SimpleDateFormat类更加灵活。

DateFormat类

  • 初始化
    //DateFormat类是抽象类,通常通过以下方法返回指定格式指定地区的格式化器    //下面的几种方法返回的格式化器只有年月日和星期    /**风格有四种:            *   - SHORT:短格式,例如:16-11-22     *   - MEDIUM:中等长度的格式,例如:2016-11-22     *   - LONG:较长的格式,例如:2016年11月22日     *   - FULL:完全形式,例如:2016年11月22日星期二     */    public static final DateFormat getDateInstance()    public static final DateFormat getDateInstance(int style)    public static final DateFormat getDateInstance(int style, Locale aLocale)    //下面的几个格式化器都会显示时间。    public static final DateFormat getDateTimeInstance()    public static final DateFormat getDateTimeInstance(int dateStyle, int timeStyle)    public static final DateFormat getDateTimeInstance(int dateStyle, int timeStyle, Locale aLocale)    public static final DateFormat getInstance()  //返回日期和时间都是用SHORT风格的默认格式化器

示例:

DateFormat df = DateFormat.getDateInstance();        DateFormat df2 = DateFormat.getDateInstance(DateFormat.SHORT);        DateFormat df3 = DateFormat.getDateInstance(DateFormat.MEDIUM);        DateFormat df4 = DateFormat.getDateInstance(DateFormat.LONG);        DateFormat df5 = DateFormat.getDateInstance(DateFormat.FULL);        DateFormat df6 = DateFormat.getDateTimeInstance();        DateFormat df7 = DateFormat.getInstance();        System.out.println(df.format(date));        System.out.println(df2.format(date));        System.out.println(df3.format(date));        System.out.println(df4.format(date));        System.out.println(df5.format(date));        System.out.println(df6.format(date));        System.out.println(df7.format(date));    //结果是这样的:    2016-11-22    16-11-22    2016-11-22    2016112220161122日 星期二    2016-11-22 23:21:01    16-11-22 下午11:21
  • 常用方法:
    public final String format(Date date) //将参数date格式化成指定字符串    public Date parse(String source) throws ParseException // 将字符串解析成date对象

SimpleDateFormat类

  • 初始化:
    SimpleDateFormat支持显示几乎所有的日历信息。可通过pattern指定显示的信息及格式。
    /**  SimpleDateFormat函数语法:  G 年代标志符  y 年  M 月  d 日  h 时 在上午或下午 (1~12)  H 时 在一天中 (0~23)  m 分  s 秒  S 毫秒  E 星期  D 一年中的第几天  F 一月中第几个星期几  w 一年中第几个星期  W 一月中第几个星期  a 上午 / 下午 标记符   k 时 在一天中 (1~24)  K 时 在上午或下午 (0~11)  z 时区 */
    public SimpleDateFormat() //默认格式为SHORT,例如:16-11-22 下午11:37    public SimpleDateFormat(String pattern)    public SimpleDateFormat(String pattern, Locale locale)    public SimpleDateFormat(String pattern, DateFormatSymbols formatSymbols)    //常用方法    public final String format(Date date)

实例:
`
SimpleDateFormat sdf = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss E”);
System.out.println(sdf.format(date));

//显示的结果为:2016-11-22 23:42:29 星期二

`

0 0
原创粉丝点击