RicoSuter / NJsonSchema

JSON Schema reader, generator and validator for .NET
http://NJsonSchema.org
MIT License
1.37k stars 529 forks source link

#1709 Generate C# TimeSpan as a DayJs duration #1714

Closed FreeFrags closed 1 month ago

FreeFrags commented 1 month ago

Attempt to generate a Dayjs duration for a C# TimeSpan.

See #1709

Im not familiar with the code however I wanted to attempt to help out.

DayJS duration takes a ISO 8601 string or an object as a constructor.

I chose to use a function to convert the 'D.HH:mm:ss.SSS' string to the object.

Im not sure if that is a good idea or if converting it to a ISO 8601 and passing that to the constructor would be more reusable.

Copilot suggests the following conversion function:

function convertToISO8601(input: string): string {
  const [days, rest] = input.split('.');
  const [hours, minutes, seconds, milliseconds] = rest.split(/[:.]/);

  // Constructing the ISO 8601 duration string
  let isoDuration = 'P';
  if (parseInt(days) > 0) isoDuration += `${parseInt(days)}D`;
  if (hours !== '00' || minutes !== '00' || seconds !== '00' || milliseconds !== '000') {
    isoDuration += 'T';
    if (parseInt(hours) > 0) isoDuration += `${parseInt(hours)}H`;
    if (parseInt(minutes) > 0) isoDuration += `${parseInt(minutes)}M`;
    if (parseInt(seconds) > 0 || parseInt(milliseconds) > 0) {
      let totalSeconds = parseInt(seconds);
      if (parseInt(milliseconds) > 0) {
        totalSeconds += parseInt(milliseconds) / 1000;
      }
      isoDuration += `${totalSeconds}S`;
    }
  }

  return isoDuration;
}

It would be best if the conversion function would be added as a function to the file as a utility which can then be called in the generated classes instead of inlined like i did here.

But im not sure how to do this and i hope someone can pick this up and polish it up.

FreeFrags commented 1 month ago

Please dont merge this. I will make a new pull request.

I realized that the dayjs duration can also be constructed with a ISO 8601.