Move date converters onto the contracts
This commit is contained in:
1 parent
6d3260db49
commit
31b114982e
6 files changed
+29
-23
No files matched your search
@@ -0,0 +1,47 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Elternbeirat.Contracts;
|
||||
|
||||
/// <summary>
|
||||
/// JSON converter that reads and writes a PocketBase date as a calendar date
|
||||
/// (<see cref="DateOnly"/>), keeping the day and dropping the time-of-day.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// PocketBase has no date-only field type: it stores every date as a UTC
|
||||
/// instant with a time-of-day (e.g. an editor's <c>2 Jan 00:00</c> Berlin is
|
||||
/// stored as <c>"2026-01-01 22:00:00.000Z"</c>). The day the editor meant is
|
||||
/// therefore the day <em>in Berlin</em>, not the day of the raw UTC string. This
|
||||
/// converter reuses the same UTC->Berlin conversion as
|
||||
/// <see cref="LocalDateTimeConverter"/> and then keeps only the date, so the day
|
||||
/// shown is the day that was entered -- with no time-of-day and no off-by-one.
|
||||
/// </remarks>
|
||||
/// <example>
|
||||
/// Apply it to a calendar-day field of a contract:
|
||||
/// <code>
|
||||
/// [JsonConverter(typeof(DateOnlyConverter))]
|
||||
/// public DateOnly Date { get; init; }
|
||||
/// </code>
|
||||
/// </example>
|
||||
/// <seealso cref="WallClock"/>
|
||||
public sealed class DateOnlyConverter : JsonConverter<DateOnly>
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
/// <exception cref="FormatException">
|
||||
/// The stored value is not a valid date string.
|
||||
/// </exception>
|
||||
public override DateOnly Read(
|
||||
ref Utf8JsonReader reader,
|
||||
Type typeToConvert,
|
||||
JsonSerializerOptions options)
|
||||
=> WallClock.Parse(reader.GetString()) is { } berlin
|
||||
? DateOnly.FromDateTime(berlin)
|
||||
: default;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override void Write(
|
||||
Utf8JsonWriter writer,
|
||||
DateOnly value,
|
||||
JsonSerializerOptions options)
|
||||
=> writer.WriteStringValue(WallClock.Format(value.ToDateTime(TimeOnly.MinValue)));
|
||||
}
|
||||
Reference in new issue
Block a user