Home > Net >  Date issues using Angular calling .net core web API and SQL Server database
Date issues using Angular calling .net core web API and SQL Server database

Time:09-27

I am using Angular and primeng p-calendar to provide me with a date picker to select a date in the past. When I save a date like the 24 Nov 82 it saves it in the database as shown below. I believe I am saving the dates as UTC, but when I save a date of the 19 Nov 1943 it puts the data to the 18th because, it is taking away an hour. When I load the 19th up back in the p-calendar it puts the date as the 18th and not the 19th?

enter image description here

Am I saving this incorrectly? or do I need to think about handling it when I load the date back up? e.g. do I need to take the UTC and convert it to my browsers timezone?

For the 24 Nov 1982 I get this when I debug the angular side:

enter image description here

For the 18 Nov 1943 I get this when I debug the angular side:

enter image description here

I have hear mention of dayjs, would this solve my problem?

Any assistance would be greatly appreciated

CodePudding user response:

The problem is that you are using DateTime, which is implicitly non-timezone-aware, instead of DateTimeOffset which is. Change your code to use the latter and it will work as expected.

CodePudding user response:

The issue was with the .net core web API, it was retuning the dates without UTC details. I implemented the DateTimeConveter as shown here:

Formatting DateTime in ASP.NET Core 3.0 using System.Text.Json

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)
    {
        writer.WriteStringValue(value.ToUniversalTime().ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ssZ"));
    }
}


// in the ConfigureServices()
services.AddControllers()
    .AddJsonOptions(options =>
     {
         options.JsonSerializerOptions.Converters.Add(new DateTimeConverter());
     });

The dates now have a Z (Zulu) at the end to signify UTC e.g.

1943-11-18T23:00:00Z

instead of the previous date like this

1943-11-18T23:00:00

The Date is now shown as the 19th instead of the 18th in the p-calendar

  • Related