在Java代码中发现一个bug,就是本来更新为时间的内容更新为一些奇怪的内容,比如20819这种形式,本来更新的时间都是近期不会超过一年,

为什么会出现这种情况,非常奇怪,遂调试下代码,跟踪发现要匹配的字符串内容和预想的日期格式不符合,代码处理这种情况是抛出异常,

然后用今天的日期替代,结果没成功,代码大概如下:

         String dt = "20160901";
SimpleDateFormat dateFm = new SimpleDateFormat("yyyyMM");
Date strSuffix = null;
try{
strSuffix = dateFm.parse(dt);
} catch(Exception e){
strSuffix = new Date();
e.printStackTrace();
} System.out.println("result date:"+strSuffix.toLocaleString());

按照本来的思路,应该是解析发生异常,然后时间为当前时间,结果打印为:2091-1-1 0:00:00

可见,就算格式和实际的不符合,也不会抛出异常,仔细检查后发现,0901也当做月份来处理,即901,然后除12的话,等于75,再加上年份2016,

刚好是2091年,这个确实和我们的预期不符,所以在做这类转化前最好确认下位数防止这种奇怪的现象。

后来了解到SimpleDateFormat的生成开销比较大,尽量少用,而且不是线程安全的函数,如果网上提供了一个高效的用法:

package com.peidasoft.dateformat;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date; public class ThreadLocalDateUtil {
private static final String date_format = "yyyy-MM-dd HH:mm:ss";
private static ThreadLocal<DateFormat> threadLocal = new ThreadLocal<DateFormat>(); public static DateFormat getDateFormat()
{
DateFormat df = threadLocal.get();
if(df==null){
df = new SimpleDateFormat(date_format);
threadLocal.set(df);
}
return df;
} public static String formatDate(Date date) throws ParseException {
return getDateFormat().format(date);
} public static Date parse(String strDate) throws ParseException {
return getDateFormat().parse(strDate);
}
}

  或者

package com.peidasoft.dateformat;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date; public class ConcurrentDateUtil { private static ThreadLocal<DateFormat> threadLocal = new ThreadLocal<DateFormat>() {
@Override
protected DateFormat initialValue() {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
}
}; public static Date parse(String dateStr) throws ParseException {
return threadLocal.get().parse(dateStr);
} public static String format(Date date) {
return threadLocal.get().format(date);
}
}

  说明:使用ThreadLocal, 也是将共享变量变为独享,线程独享肯定能比方法独享在并发环境中能减少不少创建对象的开销。如果对性能要求比较高的情况下,一般推荐使用这种方法。

关于Parse字符串为时间一次被坑经历的更多相关文章

  1. C# Oracle 时间字符串转时间类型

    C# 字符串转时间类型 yyyy-MM-dd HH:mm:ss  yyyy-MM-dd hh:mm:ss d 月中的某一天.一位数的日期没有前导零. dd 月中的某一天.一位数的日期有一个前导零. d ...

  2. python 下字符串格式时间比较

    python 下有多个有关时间的模块,分别是time.datetime.calendar,今天重点讨论下time写法. 其中time模块,主要有以下方法: ltime=time.time() 获取当前 ...

  3. postgresql数据库的 to_date 和 to_timestamp 将 字符串转换为时间格式

    数据库中:字符串 转换为 时间格式 二者区别: to_data 转换为 普通的时间格式        to_timestamp 转换可为 时间戳格式出错场景: 比较同一天 日期大小的时候,很容易出错 ...

  4. JQuery 字符串转时间格式

    //字符串转时间格式 function getDate(strDate) { var date = eval('new Date(' + strDate.replace(/\d+(?=-[^-]+$) ...

  5. c# 工具类(字符串和时间,文件)

    using System; using System.IO; using System.Text.RegularExpressions; using System.Windows.Browser; n ...

  6. java字符串、时间大小比较

    package mytest; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util ...

  7. java字符串和时间类型的相互转换

    整理的时间正则可能不全 /****** * * 是以"-" 为分隔符的 * * * * ******/ // 2012-12-03 04:07:34 reg = "\\d ...

  8. Java 字符串和时间互相转化 +时间戳

    一:字符串转换成date String datatime="2015-09-22 15:16:48"; SimpleDateFormat form = new SimpleDate ...

  9. 字符串格式时间转Date格式

    /** * 字符串时间格式转 Date 格式 * @param strDate * @return */ public static Date getDateTimeByStringTime(Stri ...

随机推荐

  1. HDU1212 Big Number 【同余定理】

    Big Number Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others) Total ...

  2. How to set up OpenERP for various timezone kindly follow the following steps to select timezone in OpenERP

        How to set up OpenERP for different Time Zones Click on the "Edit Preferences" wheel a ...

  3. 24、java操作xml方法

    XML解析方式 1. SAX解析方式 SAX(simple API for XML)是一种XML解析的替代方法.相比于DOM,SAX是一种速度更快,更有效的方法.它逐行扫描文档,一边扫描一边解析.而且 ...

  4. linux too many open files报错

    修改方法:vi /etc/security/limits.conf  增加一行,如下: *       -       nofile          65535 修改vi /etc/ssh/sshd ...

  5. nginx1.9+新增tcp/udp代理stream

    [root@rhel nginx-]# ./configure --help --help print this message --prefix=PATH set installation pref ...

  6. oracle-imp导入小错filesize设置

    ***********************************************声明*************************************************** ...

  7. hibernate4无法保存数据

    hibernate4无法保存数据 author: hiu 以后都发文章我都备注一下作者了,hiu就是我了 红色字体更新日期:2014-07-08 初次使用hibernate4,使用getCurrent ...

  8. 狄斯奎诺(dijkstra 模板)

    /*狄斯奎诺算法(dijkstra)<邻接表> */ #include<stdio.h> #include<string.h> #include<stdlib ...

  9. nyoj-----D的小L

    D的小L 时间限制:4000 ms  |           内存限制:65535 KB 难度:2   描述       一天TC的匡匡找ACM的小L玩三国杀,但是这会小L忙着哩,不想和匡匡玩但又怕匡 ...

  10. NVIDIA PureVideo Decoder解码器注册码

    http://www.amznz.com/nvidia-purevideo-decoder/ 重装系统后当然得装终极解码来看高清电影,这次为了给喜欢看HD影片的朋友,特意奉上NVIDIA7以上显卡的N ...