关于DateFormat保存时间格式和恢复

java的时间格式有2种,Date和DateTime,每种又有六个内建的日期格式

SHORT, MEDIUM, LONG, FULL, or DEFAULT

可以参看http://blog.csdn.net/sunboy_2050/article/details/7313878

import java.text.DateFormat;
import java.util.Date;

public class DateTest {
    public static void main(String[] args) {
        String strDate = null;
        
        Date date = new Date();
        System.out.println(date);            // Fri Mar 02 21:43:55 CST 2012
        
        strDate = DateFormat.getDateInstance().format(date);
        System.out.println(strDate);        // Mar 2, 2012

        
        // Date
        strDate = DateFormat.getDateInstance(DateFormat.DEFAULT).format(date);
        System.out.println(strDate);        // Mar 2, 2012

        strDate = DateFormat.getDateInstance(DateFormat.SHORT).format(date);
        System.out.println(strDate);        // 3/2/12
        
        strDate = DateFormat.getDateInstance(DateFormat.MEDIUM).format(date);
        System.out.println(strDate);        // Mar 2, 2012

        strDate = DateFormat.getDateInstance(DateFormat.LONG).format(date);
        System.out.println(strDate);        // March 2, 2012

        strDate = DateFormat.getDateInstance(DateFormat.FULL).format(date);
        System.out.println(strDate);        // Friday, March 2, 2012
        

        // DateTime
        strDate = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT).format(date);
        System.out.println(strDate);        // Mar 2, 2012 11:06:36 PM

        strDate = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT).format(date);
        System.out.println(strDate);        // 3/2/12 11:06 PM
        
        strDate = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM).format(date);
        System.out.println(strDate);        // Mar 2, 2012 11:06:36 PM

        strDate = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG).format(date);
        System.out.println(strDate);        // March 2, 2012 11:06:36 PM CST

        strDate = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL).format(date);
        System.out.println(strDate);        // Friday, March 2, 2012 11:06:36 PM CST
    }
}

 

 

这里需要注意的是short类型!!因为short类型将2012等转为了12,这就可能在某些情况下搞不清是公元12年还是被截断了的12年,所以是个不可逆的转换,其他的都还好。

而DateFormat的getInstance()方法却用的是short类型,所以在保存时会造成类型阶段截断

public static final DateFormat getInstance ()

Returns a DateFormat instance for formatting and parsing dates and times in the SHORT style for the default locale.

Returns
  • the DateFormat instance for the SHORT style and default locale.

所以最好使用相应的getDateInstance(如果只处理Date)或getDateTimeInstance(Date+Time)。如果不带参数,则使用DEFAULT类型

public static final int DEFAULT

Added in API level 1

The format style constant defining the default format style. The default is MEDIUM.

Constant Value: 2 (0x00000002)
posted @ 2013-01-26 14:40  mianlaoshu  阅读(539)  评论(0)    收藏  举报