问题:

SimpleDateFormat 是线程不安全的类,一般不要定义为static变量,如果定义为static,必须加锁,或者使用DateUtils工具类。

而且SimpleDateFormat 中的parse(String str)解析时不能为 "",否则会有ParseException

解决方法:

[正例]:

1.注意线程安全,使用DateUtils。

2.亦推荐如下处理:

 1 private static final ThreadLocal<DateFormat> df = new ThreadLocal<DateFormat>() {      
 2 
 3  @Override       
 4 
 5 protected DateFormat initialValue() {           
 6 
 7 return new SimpleDateFormat("yyyy-MM-dd");       
 8 
 9 }   
10 
11 };   

3.说明:如果是JDK8的应用,可以使用Instant代替DateLocalDateTime代替CalendarDateTimeFormatter代替Simpledateformatter,官方给出的解释:simple beautiful strong immutable thread-safe

[正例]

System.out.println(LocalDate.of(2017, 6, 7));

System.out.println(LocalTime.of(3, 20, 15));

System.out.println(LocalDateTime.of(2017, 6, 7,3, 20, 15));

System.out.println(Instant.now().atOffset(ZoneOffset.ofHours(8)));

返回结果:

2017-06-07

03:20:15

2017-06-07T03:20:15

2017-06-07T11:37:15.815+08:00

有篇文章分析的不错http://www.cnblogs.com/peida/archive/2013/05/31/3070790.html

相关文章:

  • 2021-10-14
  • 2022-12-23
  • 2022-01-22
  • 2021-08-18
  • 2021-11-14
猜你喜欢
  • 2021-12-19
  • 2021-04-24
  • 2022-01-17
相关资源
相似解决方案