7

I have a query of inner join tables:

List<Object[]> resultList = entityManager.createNativeQuery(SOME QUERY).getResultList();

When i try to access the elements of Object[] one of which is a Date I tried doing this:

for(Object[] obj : resultList) {
    Date createdDate = obj[7] !=null ? new Date(Long.valueOf(obj[7] + "")) : null;
} 

This gave obvious exception:

nested exception is java.lang.NumberFormatException: For input string: "2012-11-20"

I changed the Date to DateTime get TO_CHAR(createdDate,'DD.MM.YYYY:HH24:MI:SS')

And tried the below code:

DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
Date createdDate = null;
try {
    createdDate = df.parse(obj[7] + "");
} catch (ParseException e) {
    e.printStackTrace();
}

This approach results: createdDate = null

Any Suggestions ?

ℛɑƒæĿᴿᴹᴿ
  • 4,983
  • 4
  • 38
  • 58
tinker_fairy
  • 1,323
  • 1
  • 15
  • 18
  • 2
    You shouldn't have to parse dates cominf from a SQL query. They should come back as Date or Timestamp instances. Show us your query. – JB Nizet Dec 14 '12 at 12:07
  • `select project.project_id, project.business_id, project_status_type.project_status_desc, project.create_dtm, project.update_dtm, from project_status_type INNER JOIN project on project_status_type.project_status_type_id = project.project_status_type_id and project.project_id = 12345;` – tinker_fairy Dec 14 '12 at 12:16
  • 1
    What is the DB column type that you store date? Is it DateTime or is it VARCHAR ? If it is DateTime as @JBNizet mentioned you just need to cast your object into a java.sql.Date. If it is VARCHAR and you know the forme (e.g. 2012-11-20) then the below code snippet may be useful. – nikkatsa Dec 14 '12 at 12:20

1 Answers1

22

You shouldn't have to parse dates coming from a SQL query. They should come back as Date or Timestamp instances. Show us your query.

You prabably have java.sql.Date instances coming back, but you're transforming them to Strings by concatenating them with an empty string:

obj[7] + ""

Just do

Date createdDate = (Date) obj[7];
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255