Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a Joda Time DateTime object into a String in SQL Server format?

Tags:

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?

like image 729
sanity Avatar asked Sep 23 '10 15:09

sanity


People also ask

How do I convert DateTime to string?

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.

What is Joda-Time format?

Joda-Time provides a comprehensive formatting system. There are two layers: High level - pre-packaged constant formatters. Mid level - pattern-based, like SimpleDateFormat.


2 Answers

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);
like image 137
Vito Avatar answered Sep 20 '22 06:09

Vito


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.

like image 33
BalusC Avatar answered Sep 20 '22 06:09

BalusC