英文:
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));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论