Search code examples
.net.net-7.0asp.net-core-7.0

Datetime utc issue after migrating to .NET Core 7


I migrated a .NET Core 3 application to .NET 7. All the date fields were in DateTime data type. Since the migration the date is returning without the "Z" specifier that indicates it is an UTC Datetime.

What is the reason for this? I can put a fix by changing all the date data types DateTimeOffSet. I am not pretty sure why this is changed after the .NET migration.

public class Shipment : IAudit
{
    public Guid Id { get; set; }
    public string Title { get; set; }
    public DateTime Updated { get; set; }
    public string UpdatedBy { get; set; }
}

public class ShipmentDto
{
    public Guid Id { get; set; }
    public string Title { get; set; }
    public DateTime Updated { get; set; }
    public string UpdatedBy { get; set; }
}

//Automapper

public class ShipmentProfile : Profile
{
    public ShipmentProfile()
    {
        CreateMap<Shipment, ShipmentDto>();
        CreateMap<ShipmentDto, Shipment>();
    }
}

//Db call

public IQueryable<Shipment> GetShipments()
{
    return db.Shipments.ProjectTo<Shipment>(mapper.ConfigurationProvider);
}

response from the old endpoint, { updated: "2023-01-16T07:47:50.4462437Z" }

response from the new endpoint, { updated: "2023-01-16T07:47:50.4462437" }


Solution

  • Fixed the issue by adding the following code to startup,

    builder.Services.AddControllers().AddNewtonsoftJson(options =>
    {
        options.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc;
    });