Search code examples
c#jsontimestampunix-timestamp

Specify Epoch TimeDate Format when serializing/deserializing with Utf8Json


i couldn't find enough informations about howto handle DateTimeOffset and TimeSpan during serializing and deserializing with utf8json. i could find Infos about the IJsonFormatter, but not howto implement it correctly..

My example Class looks like this:

public MyClass()
{
 // This should be converted during serializing/deserializing  to Unix TimeStamp in Milliseconds  
  [JsonFormatter(typeof[CustomDateTimeConverter())]  
  public DateTimeOffSet? BeginDate { get; set; }

  // This should be converted to TotalMilliseconds
  public TimeSpan? Elapsed { get; set; } 
}

I have a function to convert the Datetime to EpochTimeStamp from this post: How to get the unix timestamp in C#

I tried to add [JsonFormatter(typeof[CustomDateTimeConverter())] to the datamember BeginDate, but need to implement it correctly..

public class CustomDateTimeConverter : IJsonFormatter
{
    public CustomDateTimeConverter()
    {
       // convert DateTime to Unix Milliseconds for Serialzing
    }
}

Or i am on the wrong way ? How can i achieve this ?

Thank you, for helping !


Solution

  • my solution expands my class without the use of IJsonFormatter. The Class now looks like this:

    public MyClass()
    {
    
      [IgnoreDataMember]
      // This field will be used internally
      public DateTimeOffSet? BeginDate { get; set; }
    
    
      [DataMember(Name = "beginDate")]
      // This will be used for serialzing/deserialising to Unix TimeStamp in Milliseconds 
      public long BeginDateEpoch
      {
        get { return ((DateTimeOffset)BeginDate.GetValueOrDefault()).ToUnixTimeMilliseconds(); }
        set { BeginDate= new DateTimeOffset(DateTimeOffset.FromUnixTimeMilliseconds(value).DateTime.ToLocalTime()); }
      }
    
      [IgnoreDataMember]
      public TimeSpan? Elapsed { get; set; } 
    
      [DataMember(Name = "elapsed")]
      public double ElapsedEpoch
      {
        get { return Elapsed.GetValueOrDefault().TotalMilliseconds;  }
        set { Elapsed = TimeSpan.FromMilliseconds(value); }
      }
    
    }