Java 如何将 Joda Time DateTime 对象转换为 SQL Server 格式的字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3780120/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 04:55:00  来源:igfitidea点击:

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

javasql-serverjdbcjodatime

提问by sanity

I am using the Joda-Timelibrary in Java, and have a date and time stored as an org.joda.time.DateTimeobject.

我在 Java 中使用Joda-Time库,并将日期和时间存储为org.joda.time.DateTime对象。

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?

如何可靠地将此 DateTime 对象转换为将由 SQL 服务器(包括时区)正确解析的字符串,以便我可以在 INSERT SQL 语句中使用它?

采纳答案by BalusC

Use java.sql.Timestampwith PreparedStatement#setTimestamp().

java.sql.Timestamp与 一起使用PreparedStatement#setTimestamp()

ps.setTimestamp(1, new Timestamp(dateTime.getMillis()));

Note that java.sql.Datestores only the date part, not the time part.

请注意,java.sql.Date仅存储日期部分,而不存储时间部分。

回答by vladaman

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

小心考虑时区。使用 new Timestamp() 可能会很棘手,因为它期望 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

回答by Vito

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);

回答by Joshua Pinter

Simply Function

简单的功能

I use this simple function to get a SQL-friendly date format from a JodaTimeDateTimeobject:

我使用这个简单的函数从JodaTimeDateTime对象获取 SQL 友好的日期格式:

// 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();
}