tl;博士
插入两个小时后的时刻。
myPreparedStatement // Use a `PreparedStatement` to exchange data with your database, to avoid SQL-injection risk. Use JDBC 4.2 or later for *java.time* support.
.setObject( // Fill a placeholder `?` in your SQL statement.
… , // Specify which placeholder.
OffsetDateTime // Use `OffsetDateTime` to specify a moment in JDBC 4.2. Optionally, your JDBC might support `Instant` or `ZonedDateTime` types, while support for `OffsetDateTime` is required.
.now( // Capture the current moment.
ZoneOffset.UTC // Set the offset-from-UTC to zero. We do not need to account for any time zone in this particular business scenario.
) // Returns an `OffsetDateTime` object.
.plus( // Adds a span-of-time to the moment held in the `OffsetDateTime` object.
Duration.parse( "PT2H" ) // Specify the span-of-time using standard ISO 8601 format for a duration.
) // Per Immutable Objects pattern, returns a new `OffsetDateTime` rather than changing ("mutating") the original.
)
详情
我有一个字符串值为“02:00:00”,所以基本上我需要在这个时间上加上2小时,得到需要插入的未来时间戳值
这是传达未附加到时间线的时间跨度的糟糕方式。
standard way 是PnYnMnDTnHnMnS,其中P 标志着开始,T 将年-月-日与小时-分钟-秒分开。所以 2 小时是PT2H。
要解析这样的字符串,请使用 Duration 类表示小时-分钟-秒(或 Period 表示年-月-日)。
String input = "PT2H" ;
Duration d = Duration.parse( input ) ;
你可以生成这样的字符串。
String output = Duration.ofHours( 2 ).toString() ; // Yields "PT2H" string.
捕捉UTC中的当前时刻。
OffsetDateTime odt = OffsetDateTime.now( ZoneOffset.UTC ) ;
使用标准 ISO 8601 notation 添加两个小时的持续时间。
Duration d = Duration.parse( "PT2H" ) ;
ZonedDateTime odtLater = odt.plus( d ) ; // Add 2 hours to the current moment.
使用 JDBC 4.2 或更高版本将其提交到您的数据库。
myPreparedStatement.setObject( … , odtLater ) ;
检索。
OffsetDateTime odt = myResultSet.getObject( … , OffsetDateTime.class ) ;
关于java.time
java.time 框架内置于 Java 8 及更高版本中。这些类取代了麻烦的旧 legacy 日期时间类,例如 java.util.Date、Calendar 和 SimpleDateFormat。
要了解更多信息,请参阅Oracle Tutorial。并在 Stack Overflow 上搜索许多示例和解释。规格为JSR 310。
Joda-Time 项目现在位于maintenance mode,建议迁移到java.time 类。
您可以直接与您的数据库交换 java.time 对象。使用符合JDBC 4.2 或更高版本的JDBC driver。不需要字符串,不需要java.sql.* 类。
从哪里获得 java.time 类?
ThreeTen-Extra 项目通过附加类扩展了 java.time。该项目是未来可能添加到 java.time 的试验场。您可以在这里找到一些有用的类,例如Interval、YearWeek、YearQuarter 和more。