在使用kafka获取数据的过程中, 遇到了使用SimpleDateFormat去处理时间格式的时候, 抛出错误:
Caused by: java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Long.parseLong(Long.java:601)
at java.lang.Long.parseLong(Long.java:631)
at java.text.DigitList.getLong(DigitList.java:195)
at java.text.DecimalFormat.parse(DecimalFormat.java:2051)
at java.text.SimpleDateFormat.subParse(SimpleDateFormat.java:2162)
at java.text.SimpleDateFormat.parse(SimpleDateFormat.java:1514)
at java.text.DateFormat.parse(DateFormat.java:364)
造成这种错误的原因是因为在多线程中 使用了SimpleDateFormat 非线程安全的。
解决办法1:
调用jdk 1.8版本中的 DateTimeFormatter
import java.time.format.DateTimeFormatter;
private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
将String beginTime 转为Date
LocalDateTime beginTimes = LocalDateTime.parse(beginTime, DATE_TIME_FORMATTER); ZoneId zone = ZoneId.systemDefault(); Instant instant = beginTimes.atZone(zone).toInstant(); Date paseBeginTime = Date.from(instant);
Date 转String
Instant instants = new Date().toInstant(); ZoneId zoneId = ZoneId.systemDefault(); LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zoneId); String dateStr = DATE_TIME_FORMATTER.format(localDateTime);
解决方法2:
采用线程解决:
private static ThreadLocal<DateFormat> threadLocal = new ThreadLocal<DateFormat>() { @Override protected DateFormat initialValue() { return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); } }; public static String format(Date date) { return threadLocal.get().format(date); } public static Date parse(String date){ Date dateTime = new Date(); try{ dateTime = threadLocal.get().parse(date); }catch (Exception e){ e.printStackTrace(); } return dateTime; }