FastDateFormat

1 public static final FastDateFormat ISO_DATE_FORMAT  = FastDateFormat.getInstance("yyyy-MM-dd"); 

上面的final 字段代表一个不可变的FastDateFormat,然而要让FastDateFormat字段真正的不可变,FastDateFormat内部必须遵循相应的规则才可以。

不要提供能修改对象状态的方法确保类不会被继承 
让所有字段都成为static final字段 
确保所有可变的组件不能被访问 

 
其实DateFormateUtils内部细节实现完全依靠FastDateFormat
FastDateFormat这个类编写比较复杂,它有自己的一套解析规则,同时又使用了DateFormat类的一些规则,如Pattern。与SimpleDateFormat不同,FastDateFormat是线程安全,所以这个类在多线程的服务环境中特别有用。虽然它们都继承自java.text.Format,其实FastDateFormat相当于DateFormat与SimpleDateFormat的合并,只是功能更强大而已。
 

格式化日期

问题提出:SimpleDateFormat是非线程安全的,而您又需要一个ISO格式的日期。
解决方法:使用FastDateFormat或者使用DateFormatUtils提供的静态FastDateFormat实例,它提供了一些格式化日期的线程安全的方法。

1 Date now = new Date();
2 String isoDT = DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.format(now);
3 System.out.println("It is currently: " + isoDT);

结果为:It is currently: 2014-07-02T14:38:26+08:00

如果您想使用传统的格式化类型,可以用FastDateFormat来代替SimpleDateFormat

复制代码
FastDateFormat formatter = 
    new FastDateFormat( "yyyy-mm",
                         TimeZone.getDefault( ),
                         Locale.getDefault( ) );

String output = formatter.format( new Date( ) );

System.out.println(output);

FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss").format(new Date());
复制代码

在最新的版本中FastDateFormat的构造函数已经改为protected,统一使用getInstance()来获取FastDateFormat实例,上述的输出为2014-07.

原文地址:https://www.cnblogs.com/hyl8218/p/6183408.html