3 回答

TA貢獻1818條經驗 獲得超3個贊
你可以做這樣的事情
Instant now = Instant.now();
Duration diff = Duration.between(
LocalTime.MIN,
LocalTime.parse("02:00:00")
);
Instant res = now.plus(diff);
System.out.println("res = " + Timestamp.from(res));

TA貢獻1900條經驗 獲得超5個贊
插入兩小時后的片刻。
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 小時并獲取需要插入的未來時間戳值
這是傳達與時間線無關的時間跨度的糟糕方式。
標準方式是標記開始的地方,并將年PnYnMnDTnHnMnS-月-日與小時-分鐘-秒分開。所以2小時是。PTPT2H
要解析這樣的字符串,請使用Durationclass for hours-minutes-seconds(或Periodfor years-months-days)。
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 符號添加兩個小時的持續時間。
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 ) ;
添加回答
舉報