如何在java中解析日期到日期时间

时间:2017-03-28 09:16:23

标签: java

我试图将日期时间值从javascript传递到java中的api,但它给了我这个错误:

Invalid format: "2017-03-26 00:02:51" is malformed at " 00:02:51" - IllegalArgumentException (... < DateUtil:65 < PositionApi:147 < ...)

继承人api:

@GET   
@Path("/timeLineSelectedItem/{id}/{firstDate}/{lastDate}")
public Collection<TimeLineItemSelected> get(@PathParam("id") long id,@PathParam("firstDate") String firstDate,@PathParam("lastDate") String lastDate) 
        throws SQLException {
        Collection<TimeLineItemSelected> data;    
            data=Context.getDataManager().getDataTimeLineItemSelected(id,DateUtil.parseDate(firstDate),DateUtil.parseDate(lastDate));
        return data;
    }

继承了getDataTimeLineItemSelected方法:

public Collection<TimeLineItemSelectedSTG> getDataTimeLineItemSelectedSTG(long deviceId, Date firstDate,Date lastDate) throws SQLException {
    return QueryBuilder.create(dataSource, getQuery("database.selectMapDataOfSelectedTimeLineItem"))
            .setLong("deviceId", deviceId)
            .setDate("firstDate", firstDate)
            .setDate("lastDate", lastDate)
            .executeQuery(TimeLineItemSelected.class);
}

有没有办法解决这个问题,你应该知道QueryBuilder只支持setDate而不是setDatetime ??

1 个答案:

答案 0 :(得分:0)

您只需使用SimpleDateFormat

执行此操作即可

更新

您需要创建一个将String转换为Date的方法。

public static Date convertDate(String inputDate){
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
    String dateInString = inputDate;
    Date date = null;
    try {
        date = sdf.parse(dateInString);
    }
    catch (ParseException e) {
        e.printStackTrace();
    }
    return date;
}

然后您可以像这样调用convertDate:

@GET   
@Path("/timeLineSelectedItem/{id}/{firstDate}/{lastDate}")
public Collection<TimeLineItemSelected> get(@PathParam("id") long id,@PathParam("firstDate") String firstDate,@PathParam("lastDate") String lastDate) 
        throws SQLException {
        Collection<TimeLineItemSelected> data;    
            data=Context.getDataManager().getDataTimeLineItemSelected(id, firstDate, lastDate);
        return data;
    }

ASD

public Collection<TimeLineItemSelectedSTG> getDataTimeLineItemSelectedSTG(long deviceId, String firstDateInput, String lastDateInput) throws SQLException {

    Date firstDate = convertDate(firstDateInput);
    Date lastDate = convertDate(lastDateInput);

    return QueryBuilder.create(dataSource, getQuery("database.selectMapDataOfSelectedTimeLineItem"))
            .setLong("deviceId", deviceId)
            .setDate("firstDate", firstDate.getTime())
            .setDate("lastDate", lastDate.getTime())
            .executeQuery(TimeLineItemSelected.class);
}