AWS DynamoDB SDK support for .NET DateTimeOffset

The AWS DynamoDB SDK does not support the .NET DateTimeOffset datatype by default.

You may have received an exception similar to:

System.InvalidOperationException: Type System.Nullable System.DateTimeOffset is unsupported, it cannot be instantiated. at Amazon.DynamoDBv2.DataModel

But you can add a custom IPropertyConverter so that you can persist DateTimeOffset.


public class DateTimeOffsetPropertyConverter : IPropertyConverter
{
    public static readonly string DateTimeOffsetPersistenceFormatString = "yyyy-MM-ddTHH:mm:ss.ffffzzz";

    public object FromEntry(DynamoDBEntry entry)
    {
        if (entry == null)
        {
            throw new ArgumentNullException(nameof(entry));
        }

        var primitive = entry as Primitive;

        if (primitive == null)
        {
            throw new ArgumentException($"{nameof(entry)} [{entry?.GetType()?.Name}] is not an instance of {nameof(Primitive)}.");
        }

        var dateString = primitive.Value as string;

        if (string.IsNullOrWhiteSpace(dateString))
        {
            throw new ArgumentException($"{nameof(entry)} does not contain a string primitive value.");
        }

        if (DateTimeOffset.TryParse(dateString, out var dateTimeOffset))
        {
            return dateTimeOffset;
        }

        throw new ArgumentException($"{nameof(entry)} primitive string value could not be parsed.");
    }

    public DynamoDBEntry ToEntry(object value)
    {
        if (value == null)
        {
            throw new ArgumentNullException(nameof(value));
        }

        if (value is not DateTimeOffset)
        {
            throw new ArgumentException($"{nameof(value)} [{value.GetType().Name}] is not an instance of {nameof(DateTimeOffset)}.");
        }

        var dateTimeOffset = (DateTimeOffset)value;

        var entry = new Primitive(dateTimeOffset.ToString(DateTimeOffsetPersistenceFormatString));

        return entry;
    }
}


Hope this helps,
Aaron

Comments

Popular posts from this blog

Search iPhone Text Messages with SQLite SQL Query

How to Turn Off Microsoft Arc Touch Mouse Scroll Sound Vibration

Configure SonarAnalyzer.CSharp with .editorconfig, no need for SonarCloud or SonarQube