How to set Timezone for DynamoDBAutogenerated timestamp in spring data

Hrithik Manchanda :

I am trying to add time attributes in dynamoDb table. I have added @DynamoDBAutoGeneratedTimestamp annotation on my date containers but it seems to pick the 00:00 as the default timezone.

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

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

It is not possible to set a zone offset for @DynamoDBAutoGeneratedTimestamp, but it is possible to create your own implementation of @DynamoDBAutoGenerator along with a corresponding annotation.

Here's how you would accomplish it in Java. (It looks like you're using Kotlin, but it should be straightforward for you to convert this.)

@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();
        }
    }
}

In your @DynamoDBTable class, you would use this annotation like this:

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

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=154966&siteId=1