C#C
C#15mo ago
SWEETPONY

✅ How to save to database with ISO format?

Hello, I'd like to save datetime with timezone to database. I use NodaTime for this. Let's look into my code:

BaseEntity:
public class Entity
{
    public required Guid Id { get; set; }

    public LocalDateTime CreatedAt { get; protected set; }
    
    public DateTimeZone CreatedAtTz { get; protected set; }

    protected Entity()
    {
        Id = Guid.NewGuid();
        CreatedAt = LocalDateTime.FromDateTime(DateTime.UtcNow);
        CreatedAtTz = SystemClock.Instance.GetTimeZone();
    }
}


GetTimeZone extension to automatically get time zone:
public static class DateTimeExtensions
{
    public static DateTimeZone GetTimeZone(this SystemClock systemClock)
    {
        var instance = systemClock.GetCurrentInstant();
        var zone = DateTimeZoneProviders.Bcl.GetSystemDefault();
        
        return instance.InZone(zone).Zone;
    }
}


It works good. I see almost correctly filled date and time zone in database when user creates entity.

CreatedAt should be in ISO format but it looks not like ISO format in database
image.png
Was this page helpful?