【问题标题】:How to set Timezone for DynamoDBAutogenerated timestamp in spring data如何在春季数据中为 DynamoDBAutogenerated 时间戳设置时区
【发布时间】:2019-07-17 09:39:36
【问题描述】:

我正在尝试在 dynamoDb 表中添加时间属性。我在我的日期容器上添加了@DynamoDBAutoGeneratedTimestamp 注释,但它似乎选择了 00:00 作为默认时区。

@get:DynamoDBAutoGeneratedTimestamp(strategy=DynamoDBAutoGenerateStrategy.CREATE)
    var createdAt: String? = null

    @get:DynamoDBAutoGeneratedTimestamp(strategy=DynamoDBAutoGenerateStrategy.ALWAYS)
    var updateAt: String? = null

【问题讨论】:

  • 您不能选择时区或时间偏移量。它始终使用 UTC。
  • 但是有什么办法可以让偏移量为 +05:30?
  • 就像我说的,您不能选择时区或时间偏移。为什么需要在数据库中使用偏移量?
  • 这是一个仅限区域的数据库,这可能会导致信息不正确,否则我必须手动偏移才能根据我们的时区存储正确的信息

标签: java spring-boot kotlin amazon-dynamodb


【解决方案1】:

无法为@DynamoDBAutoGeneratedTimestamp 设置区域偏移量,但可以创建自己的@DynamoDBAutoGenerator 实现以及corresponding annotation

以下是您在 Java 中实现它的方法。 (看起来您使用的是 Kotlin,但转换它应该很简单。)

@DynamoDBAutoGenerated(generator=AutoGeneratedTimestampWithOffset.Generator.class)
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface AutoGeneratedTimestampWithOffset {

    /**
     * See {@link ZoneOffset#of(String)} for valid values.
     */
    String offset();
    DynamoDBAutoGenerateStrategy strategy() default DynamoDBAutoGenerateStrategy.ALWAYS;

    public class Generator implements DynamoDBAutoGenerator<String> {
        private final String offset;
        private final DynamoDBAutoGenerateStrategy strategy;

        public Generator(final Class<String> targetType, final AutoGeneratedTimestampWithOffset annotation) {
            this.offset = annotation.offset();
            this.strategy = annotation.strategy();
        }

        @Override
        public DynamoDBAutoGenerateStrategy getGenerateStrategy() {
            return strategy;
        }

        @Override
        public final String generate(final String currentValue) {
            return OffsetDateTime.ofInstant(Instant.now(), ZoneOffset.of(offset)).toString();
        }
    }
}

在您的 @DynamoDBTable 类中,您可以像这样使用此注解:

@get:AutoGeneratedTimestampWithOffset(offset="+05:30", strategy=DynamoDBAutoGenerateStrategy.CREATE)
var createdAt: String? = null

@get:AutoGeneratedTimestampWithOffset(offset="+05:30", strategy=DynamoDBAutoGenerateStrategy.ALWAYS)
var updateAt: String? = null

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-20
    • 2016-10-09
    • 1970-01-01
    • 2015-03-14
    • 2020-06-03
    • 2019-06-18
    • 2021-08-14
    • 1970-01-01
    相关资源
    最近更新 更多