要计算两个Java java.sql.Timestamps
之间的差异,可以使用以下步骤:
java.sql.Timestamps
对象,表示要比较的时间点。Timestamp timestamp1 = Timestamp.valueOf("2022-01-01 00:00:00");
Timestamp timestamp2 = Timestamp.valueOf("2022-01-02 00:00:00");java.sql.Timestamps
对象转换为 java.time.Instant
对象。Instant instant1 = timestamp1.toInstant();
Instant instant2 = timestamp2.toInstant();java.time.Duration
类计算两个 java.time.Instant
对象之间的差异。Duration duration = Duration.between(instant1, instant2);完整的代码示例如下:
import java.sql.Timestamp;
import java.time.Duration;
import java.time.Instant;
public class TimestampDifference {
public static void main(String[] args) {
Timestamp timestamp1 = Timestamp.valueOf("2022-01-01 00:00:00");
Timestamp timestamp2 = Timestamp.valueOf("2022-01-02 00:00:00");
Instant instant1 = timestamp1.toInstant();
Instant instant2 = timestamp2.toInstant();
Duration duration = Duration.between(instant1, instant2);
long daysBetween = duration.toDays();
System.out.println("Days between: " + daysBetween);
}
}
这段代码将计算出两个 java.sql.Timestamps
对象之间的天数差异,并将其输出到控制台。
领取专属 10元无门槛券
手把手带您无忧上云