将具有当前UTC时间的日期时间插入数据库

时间:2018-11-16 02:10:00

标签: java mysql datetime java-8

我正在尝试通过sql中的GETUTCDATE()函数将当前UTC时间的日期时间插入mysql数据库。由于“功能GETUTCDATE不存在”而失败。

是否可以从Java获取sql datetime格式的当前UTC时间,然后将其作为字符串插入?

我遇到的另一个大问题是,我需要将上述utc datetime对象转换为本地时区,而我真的不知道如何通过标准的Java api来做到这一点。

2 个答案:

答案 0 :(得分:2)

tl; dr

myPreparedStatement      // Using a `PreparedStatement` avoids SQL-injection security risk.
.setObject(              // As of JDBC 4.2, we can exchange java.time objects with a database via `getObject`/`setObject` methods.
    … ,                  // Indicate which `?` placeholder in your SQL statement.
    OffsetDateTime.now( ZoneOffset.UTC )  // Capture the current moment in UTC.
) ;

java.time

现代解决方案使用的是 java.time 类,该类在几年前取代了可怕的旧日期时间类。

使用OffsetDateTime获取UTC的当前时刻。

OffsetDateTime odt = OffsetDateTime.now( ZoneOffset.UTC ) ;

MySQL 8.0的分辨率为microseconds,小数点后六位小数。 java.time 类的解析度更高,为nanoseconds。因此,您可能想从OffsetDateTimetruncate any existing nanos。用ChronoUnit指定所需的分辨率。

OffsetDateTime odt = 
    OffsetDateTime
    .now( 
        ZoneOffset.UTC 
    ) 
    .truncatedTo( ChronoUnit.MICROS ) 
;

通过PreparedStatement发送到类似于SQL标准TIMESTAMP WITH TIME ZONE数据类型的列。对于MySQL 8.0,类型为TIMESTAMP

myPreparedStatement.setObject( … , odt ) ;

并通过ResultSet进行检索。

OffsetDateTime odt = myResultSet.getObject( … , OffsetDateTime.class ) ;

要通过特定区域(时区)的人们所使用的挂钟时间的镜头来查看这一刻,请应用ZoneId来获取ZonedDateTime对象。

ZoneId z = ZoneId.of( "Asia/Kolkata" ) ;
ZonedDateTime zdt = odt.atZoneSameInstant( z ) ;  // Same moment, same point on the timeline, different wall-clock time. 

关于 java.time

java.time框架已内置在Java 8及更高版本中。这些类取代了麻烦的旧legacy日期时间类,例如java.util.DateCalendarSimpleDateFormat

目前位于Joda-Timemaintenance mode项目建议迁移到java.time类。

要了解更多信息,请参见Oracle Tutorial。并在Stack Overflow中搜索许多示例和说明。规格为JSR 310

您可以直接与数据库交换 java.time 对象。使用符合JDBC driver或更高版本的JDBC 4.2。不需要字符串,不需要java.sql.*类。

在哪里获取java.time类?

ThreeTen-Extra项目使用其他类扩展了java.time。该项目为将来可能在java.time中添加内容提供了一个试验场。您可能会在这里找到一些有用的类,例如IntervalYearWeekYearQuartermore

答案 1 :(得分:0)

您可以执行以下操作:

OffsetDateTime utc = OffsetDateTime.now(ZoneOffset.UTC);
String sql_date = utc.format(DateTimeFormatter.ofPattern("MM/dd/yyyy")); //here, you can change the format of SQL date as you need

您需要按如下所示导入类:

import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

希望有帮助。

相关问题