Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/drupal/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何将Joda Time DateTime对象转换为SQL Server格式的字符串?_Java_Sql Server_Jdbc_Jodatime - Fatal编程技术网

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

Java 如何将Joda Time DateTime对象转换为SQL Server格式的字符串?,java,sql-server,jdbc,jodatime,Java,Sql Server,Jdbc,Jodatime,我使用Java中的库,并将日期和时间存储为对象 如何将此DateTime对象可靠地转换为SQL server(包括时区)将正确解析的字符串,以便在INSERT SQL语句中使用它?与一起使用 注意只存储日期部分,而不是时间部分。 小心考虑时区。使用new Timestamp()可能很棘手,因为它需要以毫秒为单位的GMT时间 DateTime dt = new DateTime(2010, 1, 1, 14, 30, 59, 1, DateTimeZone.forOffsetHoursMi

我使用Java中的库,并将日期和时间存储为对象

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

与一起使用


注意只存储日期部分,而不是时间部分。

小心考虑时区。使用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

您可以尝试以下简单代码:

DateTime dt = new DateTime();
DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
String dtStr = fmt.print(dt);
简单功能 我使用这个简单的函数从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();
}
// 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();
}