20

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?

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
sanity
  • 35,347
  • 40
  • 135
  • 226

4 Answers4

43

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);
Vito
  • 1,080
  • 9
  • 19
10

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.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
7

Be careful to consider time zones. Using new Timestamp() may be tricky since it expects time in milliseconds in GMT.

    DateTime dt = new DateTime(2010, 1, 1, 14, 30, 59, 1, DateTimeZone.forOffsetHoursMinutes(7, 0));
    Timestamp ts = new Timestamp(dt.getMillis());
    System.out.println(dt); // prints 2010-01-01T14:30:59.001+07:00
    System.out.println(ts); // prints 2010-01-01 08:30:59.001

    DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
    String sqlTimeString = fmt.print(dt);
    System.out.println(sqlTimeString); // prints 2010-01-01 14:30:59
vladaman
  • 3,741
  • 2
  • 29
  • 26
3

Simply Function

I use this simple function to get a SQL-friendly date format from a JodaTime DateTime object:

// Converts a DateTime object into a SQL-format friendly string.
//
// Return format looks like this: 2014-01-22 10:05:34.546
//
public static String toSql(DateTime dateTime) {
    return new Timestamp( dateTime.getMillis() ).toString();
}
Joshua Pinter
  • 45,245
  • 23
  • 243
  • 245