Home > database >  Error converting value \"02:30:40\" to type 'System.TimeOnly'
Error converting value \"02:30:40\" to type 'System.TimeOnly'

Time:08-02

I am working a .net6.0 project (with postgreSql)

I want to save a start time and off time of the office into database.

I did this.

public class WorkingDay
{
    public int Id { get; set; }

    public DaysOfWeek Day { get; set; }  // enum

    public OpeningHours OpeningHours { get; set; }

    public bool IsworkingDay { get; set; }
}


public class OpeningHours
{
    public TimeOnly StartTime { get; set; }

    public TimeOnly OffTime { get; set; }

}

Now I send the data to create using POSTMAN.

{
    "Day" : 1,
    "OpeningHours" : {
        "StartTime":  "02:30:40", 
        "OffTime" :  "02:30:40"
    },
    "IsworkingDay" : false
}

I got below error. Error converting value \"02:30:40\" to type 'System.TimeOnly'. Path 'OpeningHours.OffTime',

How can I send the data for TimeOnly?

CodePudding user response:

DateOnly and TimeOnly are currently (.NET 6) not supported by System.Text.Json. However, they will be implemented in .NET 7, as by this github issue.

There are multiple workarounds for now.

  • convert them to DateTime or DateTimeOffset and back for serialization.
  • switch to .NET 7 preview for development
  • copy the .NET 7 implementation to your code (see the pull request)
  • write your own converter (an example of which can be found in this link)
  • Related