Java Instant 和 Postgres TIMESTAMPTZ 之间相差 3 位数字。

huangapple go评论67阅读模式
英文:

3 digits difference between Java Instant and Postgres TIMESTAMPTZ

问题

以下是您要求的翻译:

给定Java中的以下字段:

private Instant createdDate = Instant.now();

对应于Postgres中的以下字段:

created_date TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP;

并且使用Spring Data JDBC的CrudRepository save(S entity)保存到数据库。

在使用以下代码检查原始对象字段和保存的对象字段是否相等时:

assertThat(original_obj.getCreatedDate()).isEqualTo(database_obj.getCreatedDate());

我得到了以下不匹配:

org.opentest4j.AssertionFailedError:
      expected: 2023-05-29T10:41:12.555839137Z
       but was: 2023-05-29T10:41:12.555839Z

看起来从数据库加载的Instant比原始的Instant少了3位数字。

我如何使这两个Instant匹配?为什么它们不同?

英文:

Given the following field in Java:

private Instant createdDate = Instant.now();

corresponding to the following field in Postgres:

created_date TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP;

and saved to database using Spring Data JDBC CrudRepository save(S entity).

When checking for equality the original object field and the saved one with:

assertThat(original_obj.getCreatedDate()).isEqualTo(database_obj.getCreatedDate());

I get the following mismatch:

org.opentest4j.AssertionFailedError:
      expected: 2023-05-29T10:41:12.555839137Z
       but was: 2023-05-29T10:41:12.555839Z

It appears the Instant loaded from database has 3 less digits than the original Instant.

How can I make the two instants match? Why are they different?

答案1

得分: 5

Java Time以最多1纳秒的精度存储时间,而Postgres以微秒为单位存储时间。

您可以按照评论中建议的方式允许比较中的差值,或者更简单的解决方案是,如果您不关心纳秒,只需在Java中截断日期:

Instant createdDate = Instant.now().truncatedTo(ChronoUnit.MICROS)
英文:

Java Time stores time with up to 1 nanosecond precision, while Postgres stores microseconds.

You can either allow delta in the comparison as suggested in the comments or.. an easier solution would be to just truncate the date in Java if you don't care about those nanos:

Instant createdDate = Instant.now().truncatedTo(ChronoUnit.MICROS)

答案2

得分: 3

If you prefer not to truncate the expected value, isCloseTo and byLessThan could help:

assertThat(original_obj.getCreatedDate()).isCloseTo(database_obj.getCreatedDate(), byLessThan(1, ChronoUnit.MICROS));
英文:

If you prefer not to truncate the expected value, isCloseTo and byLessThan could help:

assertThat(original_obj.getCreatedDate()).isCloseTo(database_obj.getCreatedDate(), byLessThan(1, ChronoUnit.MICROS));

huangapple
  • 本文由 发表于 2023年5月29日 18:50:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/76356696.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定