If this is for a time stamp for your SQL database: don’t give your database a time stamp as a string. Give it a proper date-time object. Since JDBC 4.2 this means:
- For an SQL
timestamp with time zone (recommended for the vast majority of purposes) provide an OffsetDateTime; many drivers accept an Instant too.
- For an SQL
timestamp without time zone provide a LocalDateTime.
So for example:
java.sql.Date inputDate = getFromSomewhere();
OffsetDateTime dateTimeForDatabase = inputDate.toLocalDate()
.atStartOfDay(ZoneOffset.UTC)
.toOffsetDateTime();
System.out.println(dateTimeForDatabase);
PreparedStatement stmt = yourDatabaseConnection.prepareStatement(
"insert into your_table(your_timestamp_col) values (?)");
stmt.setObject(1, dateTimeForDatabase);
int rowsInserted = stmt.executeUpdate();
Example output from the print statement in the middle:
2019-09-29T00:00Z
The Z means UTC, so this is the same point in time as the 2019-09-28 20:00:00.0 you asked for, assuming that your JVM’s time zone is some variant of North American Eastern Time (America/Toronto or America/New_York).
The object that you see in your debugger looks very much like a java.sql.Date object, so I have taken this type as my starting point. The java.sql.Date class is poorly designed, though, in fact a true hack on top of the already poorly designed java.util.Date class. It is also long outdated. So if you could get a modern type instead, for example a LocalDate, it would be advantageous.
What went wrong in your code?
A LocalDate is a date without time of day, for example 2019-09-29. You were trying to format one using the format pattern yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. So you are asking to include the time of day in the result, but as I said, the LocalDate hasn’t got a time of day, so this does not make sense. The error message that you got was actually pretty precise:
Unsupported field: HourOfDay
date.toString()is a bad idea as the format not specified and could change. It looks like you have ajava.util.Dateandjava.util.Calendar.LocalDatealso has no concept of time, so you'll need to provide some means to inject that (ieLocalDatetoLocalDateTime:/)2019-09-29T00:00:00.000-0400is same time as2019-09-29 04:00:00UTC, not2019-09-28 20:00:00.0, so unless you're in time zoneAmerica/New_Yorkand targeting time zone-08:00(America/Anchorage), your values don't make sense.OffsetDateTme, anInstantor aLocalDateTime.