java日期格式化中ParsePosition问…

来源:互联网 发布:笨方法学python ex49 编辑:程序博客网 时间:2024/06/08 16:20

String data = "Fri Nov 28 00:00:00 CST 2008";

Date date = DateFormat.getDateInstance().parse(date);

会报错误ParseException

 

这是因为DateFormat中源码

    publicDate parse(String source) throws ParseException
    {
       ParsePosition pos = new ParsePosition(0);
       Date result = parse(source, pos);
       if (pos.index == 0)
           throw new ParseException("Unparseable date: /"" + source + "/"",
               pos.errorIndex);
       return result;
    }

所以要使用下面的方式DateFormat.getDateInstance().parse(date,newParsePosition(1))

//实例

public static Timestamp stringToTimestamp(String timestampStr){

if (timestampStr == null || timestampStr.trim().equals("")){

return null;

}

SimpleDateFormat formatter = newSimpleDateFormat("yyyy-MM-dd");

ParsePosition pos = new ParsePosition(0);

Date datetime = formatter.parse(timestampStr, pos);

return new Timestamp(datetime.getTime());


}

0 0
原创粉丝点击