Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conversion of java object to Date or DateTime

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 ?

like image 204
tinker_fairy Avatar asked Dec 14 '12 11:12

tinker_fairy


People also ask

Which converter is used for a Date and time conversion in java?

Class DateTimeConverter. Converter implementation for java.

Does Date convert object to string?

Get the date to be converted. Create an instance of SimpleDateFormat class to format the string representation of the date object. Get the date using the Calendar object. Convert the given date into a string using format() method.

Is there a Date object in java?

Allocates a Date object and initializes it to represent the specified number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT. Parameters: date - the milliseconds since January 1, 1970, 00:00:00 GMT.


1 Answers

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];
like image 67
JB Nizet Avatar answered Sep 30 '22 09:09

JB Nizet