2

I have a datetime type column in mysql db and file fetching column using jdbctemplate and type casting it to java.util.Date throws error. Here is my code :

I have defined the following SimpleDateFormat

private static final SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

and use it like this

String query = "select start_time as starttime from job_tbl";

List<Map<String, Object>> myList = jdbcTemplate.queryForList(query);

for (Map<String, Object> map: myList) {
    String dateTime = dateformat.format((java.util.Date) map.get("starttime");
}

The code throws this error:

java.lang.ClassCastException:
java.time.LocalDateTime cannot be cast to java.util.Date

The same functionality was working fine in my old other projects with jdbcTemplate easily type casted to java.util.Date but in this new project, it returns date of format java.time.LocalDateTime, is there any issue with mysql-connector or any other issue??

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
  • I recommend you don’t use `SimpleDateFormat` and `java.util.Date`. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead use `LocalDateTime` and `DateTimeFormatter`, both from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Aug 15 '21 at 07:13

3 Answers3

4

java.time

The java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.

From the error, it is clear that you need to cast map.get("starttime") to java.time.LocalDateTime instead of java.util.Date.

DateTimeFormatter dft = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss", Locale.ENGLISH);
String dateTime = dft.format((java.time.LocalDateTime) map.get("starttime"));   

Learn more about the modern Date-Time API* from Trail: Date Time.


* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
  • 1
    Thanks Arvind, your solution helped!. But, still I have doubt the same functionality was working fine in my old other projects with jdbcTempate easily type casted to java.util.Date but in this new project, it returns date of format java.time.LocalDateTime, is there any issue with mysql-connector or any other issue? – Vinayak Nair Aug 13 '21 at 09:03
  • 2
    I am not sure until I debug the code or look into the code and configuration. Since JDBC 4.2, it is recommended to switch to `java.time`. Check [this answer](https://stackoverflow.com/a/67752047/10819573) and [this answer](https://stackoverflow.com/a/67505173/10819573) to learn more about using `java.time` API with JDBC. – Arvind Kumar Avinash Aug 13 '21 at 09:12
2

For those arriving at this post after upgrading Spring Boot: The Connector/J switched to java.time classes with version 8.0.23. If you really need to keep working with util classes, override the version

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.22</version>
    </dependency>

But, as others have said, the clean solution is to upgrade your code to the new java.time package.

Simon
  • 2,994
  • 3
  • 28
  • 37
0

Why do you need to cast it to Date. As per the logic you just need the string from the datatime.

Format LocalDateTime to String

// Get current date time
LocalDateTime currentDateTime = LocalDateTime.now();
 
// Inbuilt format
static DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE_TIME;
 
// Custom format
//DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
 
// Format LocalDateTime
String formattedDateTime = currentDateTime.format(formatter);
 
//Verify
System.out.println("Formatted LocalDateTime : " + formattedDateTime);       
 
//Output:
 
//Formatted LocalDateTime : 2018-07-14T17:45:55.9483536

more details can be found here: How to parse/format dates with LocalDateTime? (Java 8)

Nagaraju Chitimilla
  • 530
  • 3
  • 7
  • 23
  • The data available in table is in the format: '2021-08-13 13:32:59' and I want to store it in String in same format, but by applying above logic as mentioned by You, the date is in the format: //Formatted LocalDateTime : 2018-07-14T17:45:55.9483536. My issue is why jdbcTempalate providing data in java.time.LocalDateTime? – Vinayak Nair Aug 13 '21 at 08:58
  • That's to give an idea on how you can proceed with your solution. By just changing the Pattern you can achieve the solution. – Nagaraju Chitimilla Aug 13 '21 at 09:06