I looked into your previous Stack Overflow question for some context. Please don’t expect that Stack Overflow users will usually do this. They will not.
As I understand it, Task
is org.jfree.data.gantt.Task
from JFreeChart, and its constructor requires two java.util.Date
arguments (start and end). You are getting java.sql.Date
objects from your database.
While you cannot (reasonably) change JFreeChart, since JDBC 4.2 you can take advantage of getting modern LocalDate
objects rather than old-fashioned java.sql.Date
objects from your database:
while (rs.next()) {
String a = rs.getString("TITRE");
LocalDate startDate = rs.getObject("DATE DEBUT Prévi", LocalDate.class);
LocalDate endDate = rs.getObject("DATE FIN prévi", LocalDate.class);
series1.add(new Task(a,
Date.from(startDate.atStartOfDay().toInstant(ZoneOffset.UTC)),
Date.from(endDate.atStartOfDay().toInstant(ZoneOffset.UTC))
)
);
}
I found it simpler not to put your fetched data into separate lists and taking it out again before constructing the Task
objects. In your code please do as you find best.
PS The getXxx
methods of java.sql.Date
and java.util.Date
are deprecated because they work unreliably across time zones, so even if you couldn’t avoid those classes, never call those methods. If you do get a java.sql.Date
from somewhere, the first thing to do is call its toLocalDate
method to convert it to a modern LocalDate
.
EDIT: You are doing very much in a single statement with nested method calls. I agree with the comment by Basil Bourque that this can be hard for a reader (and yourself?) to follow. I believe that this was also part of why people (including myself) didn’t understand your question. We suggest breaking it up. One example would be:
Instant startInstant = startDate.atStartOfDay().toInstant(ZoneOffset.UTC);
Date startUtilDate = Date.from(startInstant);
// Similarly for end date
Task newTask = new Task(a, startUtilDate, endUtilDate);
series1.add(newTask);
It’s wordier, but each step is easy to follow now.
Instead of startDate.atStartOfDay().toInstant(ZoneOffset.UTC)
I usually do startDate.atStartOfDay(ZoneOffset.UTC).toInstant()
, but that’s a matter of taste or habit. The result is the same in both cases.
Links