java日期格式化中ParsePosition问…

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

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

会报错误ParseException

 

这是因为DateFormat中源码

    public Date 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,new ParsePosition(1))

//实例

public static Timestamp stringToTimestamp(String timestampStr) {

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

return null;

}

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

ParsePosition pos = new ParsePosition(0);

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

return new Timestamp(datetime.getTime());


}

你可能感兴趣的:(java)