I am writing code to insert values from CSV files to MySQL DB. one of the SQL columns is DateTime.
I get the value created from CSV and its this: 07/07/10 08:08
Timestamp sqlTimestampCreated = Timestamp.valueOf(String.valueOf(created));
statement.setTimestamp(6, sqlTimestampCreated);
how to convert ‘created’ to Datetime and set it to prepared Statement?
2
Answers
Use SimpleDateFormat class to format your date object in the required format i.e
yyyy-mm-dd hh:mm:ss
in your case.Below is the code to format date using SimpleDateFormat class –
tl;dr
You said:
Avoid legacy date-time classes
You are using terribly flawed date-time classes that were years ago supplanted by the modern java.time classes defined in JSR 310. Avoid using
Calendar
, eitherDate
,Timestamp
,SimpleDateFormat
, etc.ISO 8601
I suggest educating the publisher of your data about the virtues in following the ISO 8601 standard for textual representations of date-time values.
The java.time classes use the standard ISO 8601 formats by default when parsing/generating text.
The standard format for a date with time but no offset or time zone: YYYY-MM-DD’T’HH:MM.
java.time
Parse your input as a
LocalDateTime
object.Define a formatting pattern to match your input, using
DateTimeFormatter
class.See this code run at Ideone.com.
Write to your
DATETIME
column in MySQL.Retrieve.
All this has been covered many times on Stack Overflow. Search to learn more.