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

    Date now = new Date();
    String isoDT 
= DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.format(now);
    System.out.println(
"It is currently: " + isoDT);
结果为It is currently: 2006-03-08T10:44:29+08:00
如果您想使用传统的格式化类型,可以用
FastDateFormat来代替SimpleDateFormat,
// create a formatter that simply prints the year and month

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

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

System.out.println(output);
在最新的版本中FastDateFormat的构造函数已经改为protected,统一使用getInstance()来获取FastDateFormat实例,上述的输出为2006-03.
Discussion:In fact, you should be aware that none of the Sun formatting classes are thread-safe.
以下是DateFormatUtils里面提供的Static date/time formats。

Name

Format

ISO_DATE_FORMAT

yyyy-MM-dd"2004-01-02"

ISO_DATE_TIME_ZONE_FORMAT

yyyy-MM-ddZZ"2004-01-02-07:00"

ISO_DATETIME_FORMAT

yyyy-MM-dd'T'HH:mm:ss"2004-01-02T23:22:12"

ISO_DATETIME_TIME_ZONE_FORMAT

yyyy-MM-dd'T'HH:mm:ssZZ"2004-01-02T21:13:45-07:00"

ISO_TIME_FORMAT

'T'HH:mm:ss"T04:23:22"

ISO_TIME_NO_T_FORMAT

HH:mm:ss"05:12:34"

ISO_TIME_NO_T_TIME_ZONE_FORMAT

HH:mm:ssZZ"12:32:22-07:00"

ISO_TIME_TIME_ZONE_FORMAT

'T'HH:mm:ssZZ"T18:23:22-07:00"

SMTP_DATETIME_FORMAT

EEE, dd MMM yyyy HH:mm:ss Z"Wed, 01 Feb 2004 20:03:01 CST"

评论
发表评论

您还没有登录,请登录后发表评论