S S
S S

Reputation: 39

DateOnly & TimeOnly Web API .NET 6

I'm having difficulties on sending the value of DateOnly & TimeOnly in .Net 6 to database.

I have read multiple answers here on this issue, and have tried it all but its still showing error 400

heres the converter I made

 public class DateOnlyJsonConverter : JsonConverter<DateOnly>
    {
      
        public override DateOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            var value = reader.GetString();

            return DateOnly.Parse(value!);
        }

        public override void Write(Utf8JsonWriter writer, DateOnly value, JsonSerializerOptions options)
        {
            writer.WriteStringValue(value.ToString("yyyy-MM-dd"));
        }

for the TimeOnly

public class TimeOnlyJsonConverter : JsonConverter<TimeOnly>
    {
        public override TimeOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            var value = reader.GetString();

            return TimeOnly.Parse(value!); 
        }

        public override void Write(Utf8JsonWriter writer, TimeOnly value, JsonSerializerOptions options)
        {
            writer.WriteStringValue(value.ToString("HH:mm:ss.fff"));
        }
    }

I have also added this on the program.cs

builder.Services.AddControllers().AddJsonOptions(
    options =>
    {
        options.JsonSerializerOptions.Converters.Add(new DateOnlyJsonConverter());
        options.JsonSerializerOptions.Converters.Add(new TimeOnlyJsonConverter());
    }

and this is the code on the controller

    [HttpPost]
            public async Task<IActionResult> CheckIn(Absensi request)
            {
                 var absensis = new Absensi()
                {
                    IDKaryawan = request.IDKaryawan,
                    NamaKaryawan = request.NamaKaryawan,
                    IDPerusahaan = request.IDKaryawan,
                    NamaPerusahaan = request.NamaKaryawan,
                     Tanggal = DateOnly.FromDateTime(DateTime.Now),
                    WaktuCheckIn = TimeOnly.FromDateTime(DateTime.Now),
                   // WaktuCheckOut = TimeOnly.FromDateTime(DateTime.Now),
                 };
                await _context.Absensis.AddAsync(absensis);
                await _context.SaveChangesAsync();
                return Ok("Absensi Created!");
            }

yet, when its still showing error 400 when executed thru swagger

{ 
 "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
 "title": "One or more validation errors occurred.",
 "status": 400,
 "traceId": "00-6756849f7366cabf4b0d7d8289fc4173-53ac44cc08885df5-00",
 "errors": {
        "request": [
        "The request field is required."
       ],
"$.tanggal": [
  "The JSON value could not be converted to System.DateOnly. Path: $.tanggal | LineNumber: 5 | BytePositionInLine: 14."
  ]
 }
}

error 400 swagger

edit : to add absensi class & json

public partial class Absensi
    {
        public string IDKaryawan { get; set; } = null!;
        public string NamaKaryawan { get; set; } = null!;
        public string IDPerusahaan { get; set; } = null!;
        public string NamaPerusahaan { get; set; } = null!;
        [JsonConverter(typeof(DateOnlyJsonConverter))] 
        public DateOnly? Tanggal { get; set; }
        [JsonConverter(typeof(TimeOnlyJsonConverter))]
        public TimeOnly? WaktuCheckIn { get; set; }
        [JsonConverter(typeof(TimeOnlyJsonConverter))]
        public TimeOnly? WaktuCheckOut { get; set; } 
        public int Id { get; set; }

    }
}

json

"tanggal": {
    "year": 0,
    "month": 0,
    "day": 0,
    "dayOfWeek": 0
  },
  "waktuCheckIn": {
    "hour": 0,
    "minute": 0,
    "second": 0,
    "millisecond": 0,
    "ticks": 0
  },
  "waktuCheckOut": {
    "hour": 0,
    "minute": 0,
    "second": 0,
    "millisecond": 0,
    "ticks": 0
  },

Please let me know what i have done and how to fix it. thank you

Upvotes: 3

Views: 2210

Answers (1)

Pablo Recalde
Pablo Recalde

Reputation: 3571

I think you're missing the attribute that tells the Json parser to use your specific converter for that property.

On the Absensi type, you need to decorate the property of type DateOnly like this:

public class Absensi 
{
    [JsonConverter(typeof(DateOnlyJsonConverter))]
    public DateOnly MyDateOnlyProperty { get; set; }
    ...
}

Upvotes: 1

Related Questions