convert string date to sql date format
I want to convert this string "2022-01-13 14:33:07.996" to java sql date. I have read the answers and I have converted the string to java util date and then to java sql date. I just don't know how to get the full date in java sql date format
String dateStart = "2022-01-13 14:33:07.996";
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date date1 = dateFormat.parse(dateStart);
java.util.Date utilDate = date1;
java.sql.Date sqlDate = new java.sql.Date(date1.getTime());
System.out.println(sqlDate);
in out put i get this
2022-01-13
but I want something like this 2022-01-13 14:33:07.996
in java sql date format
tl;dr
To write date-time values to a database, use appropriate objects, not text. For a date-only value, use LocalDate
.
myPreparedStatement
.setObject(
… ,
LocalDateTime
.parse( "2022-01-13 14:33:07.996".replace( " " , "T" ) )
.toLocalDate()
)
Avoid legacy date-time classes
You are using terrible date-time classes that were years ago supplanted by the modern java.time classes defined in JSR 310.
Date-only
You said:
2022-01-13 14:33:07.996 in java sql date format
That is a contradiction. A java.sql.Date
object represents a date-only, not a date with time-of-day.
java.time.LocalDateTime
Parse your input string as a LocalDateTime
because it lacks any indicator of time zone or offset. Replace the SPACE in the middle with a T
to comply with the ISO 8601 standard.
String input = "2022-01-13 14:33:07.996".replace( " " , "T" ) ;
LocalDateTime ldt = LocalDateTime.parse( input ) ;
java.time.LocalDate
Extract the date portion.
LocalDate ld = ldt.toLocalDate() ;
Database access
Write to database.
myPreparedStatement.setObject( … , ld ) ;
Retrieve from database.
LocalDate ld = myResultSet.getObject( … , LocalDate.class ) ;
These matters have been covered many many times already on Stack Overflow. Search to learn more.