Skip to content

Deserialization of timestamps in CouchActiveTask incorrect #211

@nefarius

Description

@nefarius

The properties StartedOn and UpdatedOn are currently converted into the wrong format. From CouchDB docs:

started_on (number) – Task start time as unix timestamp
updated_on (number) – Unix timestamp of last operation update

Current

Image

Fixed

Image

The fix is simple; I added a new converter:

using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

namespace CouchDB.Driver.Helpers;

public class UnixTimestampSecondsConverter : DateTimeConverterBase
{
    private static readonly DateTime Epoch =
        new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        if (value is DateTime dt)
        {
            var seconds = (long)(dt.ToUniversalTime() - Epoch).TotalSeconds;
            writer.WriteValue(seconds);
        }
        else
        {
            throw new JsonSerializationException("Expected DateTime object.");
        }
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        switch (reader.Value)
        {
            case null:
                return null!;
            case long seconds:
            case string str when long.TryParse(str, out seconds):
                return Epoch.AddSeconds(seconds);
            default:
                throw new JsonSerializationException("Expected integer Unix timestamp in seconds.");
        }
    }
}

Currently testing it. Can PR soon too ofc. 😉

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions