SimpleDateFormatNumber FormatException 格式化错误

编程入门 行业动态 更新时间:2024-10-25 23:38:23

SimpleDateFormatNumber FormatException 格式化<a href=https://www.elefans.com/category/jswz/34/1771449.html style=错误"/>

SimpleDateFormatNumber FormatException 格式化错误

看源码,发现 SimpleDateFormatNumber 不是线程安全的类。

 * Date formats are not synchronized.* It is recommended to create separate format instances for each thread.* If multiple threads access a format concurrently, it must be synchronized* externally.

因为,SimpleDateFormat继承了DateFormat,在DateFormat中定义了一个protected属性的 Calendar类的对象:calendar。只是因为Calendar累的概念复杂,牵扯到时区与本地化等等,Jdk的实现中使用了成员变量来传递参数,这就造成在多线程的时候会出现错误。

 

这样写,在高并发的情况下会出现  java.lang.NumberFormatException: For input string: ""

public class DateUtil {private DateUtil(){}private static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");public static Date parse(String date)  throws ParseException {return DATE_FORMAT.parse(date);}    }

改成:

public class DateUtil {private DateUtil(){}public static Date parse(String date)  throws ParseException {return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(date);}    }

或者: 

public class DateUtil {private DateUtil(){}private static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");public static Date parse(String date)  throws ParseException {synchronized(DATE_FORMAT){return DATE_FORMAT.parse(date);}}    }

 

 

附JDK1.8时间获取

        //JDK1.8时间获取当前时间String now = LocalDateTime.now().withNano(0).toString().replace("T", " ");String now = LocalDate.now()+" "+LocalTime.now().withNano(0).toString();

 

更多推荐

SimpleDateFormatNumber FormatException 格式化错误

本文发布于:2024-03-10 01:19:31,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1726652.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:错误   SimpleDateFormatNumber   FormatException

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!