[英]How do I convert a Joda Time DateTime object into a String in SQL Server format?
I am using the Joda-Time library in Java, and have a date and time stored as an org.joda.time.DateTime object. 我在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服务器(包括时区)正确解析的String,以便我可以在INSERT SQL语句中使用它?
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()
. 将java.sql.Timestamp
与PreparedStatement#setTimestamp()
。
ps.setTimestamp(1, new Timestamp(dateTime.getMillis()));
Note that java.sql.Date
stores only the date part, not the time part. 请注意, java.sql.Date
仅存储日期部分,而不存储时间部分。
Be careful to consider time zones. 小心考虑时区。 Using new Timestamp() may be tricky since it expects time in milliseconds in GMT. 使用新的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
I use this simple function to get a SQL-friendly date format from a JodaTime DateTime
object: 我使用这个简单的函数从JodaTime DateTime
对象获取一个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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.