I am using the Joda-Time library in Java, and have a date and time stored as an org.joda.time.DateTime object.
How can I reliably convert this DateTime object into a String that will be parsed correctly by SQL server (including timezone), such that I can use it in an INSERT SQL statement?
In order to convert a DateTime to a string, we can use CONVERT() and CAST() function. These functions are used to converts a value(of any datatype) into a specified datatype.
Joda-Time provides a comprehensive formatting system. There are two layers: High level - pre-packaged constant formatters. Mid level - pattern-based, like SimpleDateFormat.
you can try this simple code :
DateTime dt = new DateTime();
DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
String dtStr = fmt.print(dt);
Use java.sql.Timestamp
with PreparedStatement#setTimestamp()
.
ps.setTimestamp(1, new Timestamp(dateTime.getMillis()));
Note that java.sql.Date
stores only the date part, not the time part.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With