输入字符串的Java util.numberFormatException:" 2014-01-12 05-44-56"

时间:2015-02-08 11:07:50

标签: java

我是OFBiz和Java的新手。我使用下面的代码块来检查日期时间输入并使用它来搜索表格。

Timestamp strtDate = UtilDateTime.getTimestamp((String)request.getParameter("strt_date"));
if(strtDate != null)
{
     // then here i used the date for taking data.
}

当我填写表单的日期时间字段进行搜索时,或者当没有选择日期来搜索显示numberFormatException的错误时,我怎么能解决这个问题?感谢您的帮助和指导。

3 个答案:

答案 0 :(得分:2)

基于Apache ofbiz API看起来UtilDateTime#getTimestamp(String)需要毫秒值。你正在传递"2014-01-12 05-44-56"。您需要先解析日期。使用纯1.8之前的java(请记住,格式化程序不是线程安全的):

String dateString = "2014-01-12 05-44-56";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
Date date = formatter.parse(dateString);
UtilDateTime.getTimestamp(date.getTime());

自java 1.8(高度建议切换后,如果可以!):

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH-mm-ss");
ZonedDateTime date = ZonedDateTime.parse(text, formatter);
long millis = date.toInstant().toEpochMilli();

答案 1 :(得分:0)

你必须以毫秒为单位传递时间,而不是传递时间。

您也可以查看代码:

public static Timestamp getTimestamp(String milliSecs) throws NumberFormatException {
    return new Timestamp(Long.parseLong(milliSecs));
}

它将解析您传递的long数据,并且该值应该是有效的long值。

答案 2 :(得分:0)

request.getParameter("strt_date")无论如何都会返回String,因此无需将其明确强制转换为String。此外,Client和{}之间会有一份合同。 Server所需的日期格式。因此,您必须使用SimpleDateFormat以相同的格式解析String-Date。代码展望将如下所示:

SimpleDateFormat formatter = new SimpleDateFormat("contract-date-format");
Date date = formatter.parse(request.getParameter("strt_date"));
UtilDateTime.getTimestamp(date.getTime());