New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[Question] DateTimeOffset? protobuf serialization/deserialization in ASP Core #226
Comments
Your surrogate should be using System;
using System.Runtime.Serialization;
namespace ProtobufNetTest
{
[DataContract(Name = nameof(DateTimeOffset))]
public class DateTimeOffsetSurrogate
{
[DataMember(Order = 1)]
public long? Value { get; set; }
public static implicit operator DateTimeOffset(DateTimeOffsetSurrogate surrogate)
{
return DateTimeOffset.FromUnixTimeMilliseconds(surrogate.Value.Value);
}
public static implicit operator DateTimeOffset?(DateTimeOffsetSurrogate surrogate)
{
return surrogate != null ? DateTimeOffset.FromUnixTimeMilliseconds(surrogate.Value.Value) : (DateTimeOffset?)null;
}
public static implicit operator DateTimeOffsetSurrogate(DateTimeOffset source)
{
return new DateTimeOffsetSurrogate
{
Value = source.ToUnixTimeMilliseconds()
};
}
public static implicit operator DateTimeOffsetSurrogate(DateTimeOffset? source)
{
return new DateTimeOffsetSurrogate
{
Value = source?.ToUnixTimeMilliseconds()
};
}
}
} |
Thanks! I will try it, but why surrogate can't use string and how to register surrogate correctly? When I was debugging I did not see that the surrogate was called, so i think my problem with surrogate registration. |
The way you registered surrogates is correct however your class has a Sure you can serialize the value as a string. I used long and the unix time value because the output is smaller than the string representation and faster than converting to/from a string. |
Thanks for answer! I specifically did not delete the commented lines in code block in my question, I tried it, but without success. How does converting to UnixTime support the time zone? |
By definition it takes into account the time zone since unix time starts at 1/1/1970 00:00:00 (UTC) |
The purpose of DateTimeOffset is to preserve TimeZone information so it's possible to see at white Offset the timestamp was generated. By convertig to unixtime this information is lost. |
Hi!
After some investigation and reading posts on SO I found two ways to serialize DateTimeOffset?
In my StartUp file I use
My surrogate class
My serialized class
When I try serialize/deserialize StocksDto, Date property return no value (null). As I can see implicit operator in surrogate does not called.
How to use surrogate for DateTimeOffset? in my case?
The text was updated successfully, but these errors were encountered: