I am developing a WebApp which is going to be deployed on Azure. Because it has to be server indipendent, I think I have to store the DateTime
as UTC, so my Postgres
column is configured as timestamp without time zone
and when I save a date I put the utc value, let say e.g 2021-10-14 06:16:33.813473
. In this case the value returned to the client is the same since the Kind
value server side is Unspecified
and by parsing it using Date
or dayjs
and formatting it for the rendering, I get 14.10.2021 06:16
since I am at GMT+2
, which is wrong, the desired output is 14.10.2021 08:16
.
To fix it I could simply add the Z
when parsing the date, as new Date("2021-10-14 06:16:33.813473" + "Z")
but I think it's not a clean solution.
I could define the column as timestamp with time zone
, suppose we have the same value in the db, but with time zone information: 2021-10-14 06:16:33.813473+00
, to the client it is returned as 2021-10-14T08:16:33.813473+02:00
and on formatting it as previously I get the desired result. But in this case I have the problem saving the timestamps. If I save DateTime.UtcNow
in the database I find the current time - 4 hours (instead of 2).
Another possible solution would be still have the column defined as timestamp without time zone
as in the first example, having the date 2021-10-14 06:16:33.813473
and adding a JsonSerializerOption
:
public class DateTimeConverter : JsonConverter<DateTime>
{
public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
return DateTime.Parse(reader.GetString());
}
public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
{
string s = value.ToString("O");
if (value.Kind == DateTimeKind.Unspecified)
{
s += "Z";
}
writer.WriteStringValue(s);
}
}
It works as expected, but IF I have another column defined as date
, this also gets the Z
and on the client the parsed value has the 2 hourses added.
How sould I do?
What problems could I encounter IF I use timestamp with time zone
columns and set DateTime.Now
instead DateTime.UtcNow
?
PS. I am working with EF Core 5 and Microsoft.AspNetCore.Mvc.Core 5