commandline icon indicating copy to clipboard operation
commandline copied to clipboard

DateOnly not supported

Open Ashthos opened this issue 3 years ago • 1 comments

The DateOnly data type causes a NotSupportedException to be thrown when calling ParseArguments.

v2.9.1 from Nuget.

public class CommandLineOptions
  {
      [Option('v', "verbose", Required = false, HelpText = "Set output to verbose messages.")]
      public bool Verbose { get; set; }

      [Option('d', "business-date", Required = true, HelpText = "The date (yyyy-mm-dd) to run the process for.")]
      public DateTime Works { get; set; }

      [Option('e', "run-date", Required = true, HelpText = "The date (yyyy-mm-dd) to run the process for.")]
      public DateOnly Fails { get; set; }
  }

Workaround: Use DateTime instead and do an explicit conversion when property is used DateOnly.FromDateTime(value);

Ashthos avatar Oct 19 '22 10:10 Ashthos

Yeah, this is because Microsoft added DateOnly and TimeOnly in .NET 6 but stupidly neglected to add built-in TypeConverters for them. This will be fixed in .NET 7 but until then:

  • add DateOnlyConverter.cs to your project (you will need to adjust the SR stuff)
  • bind it to DateOnly via TypeDescriptor before you invoke CommandLineParser (so ideally, first line in Program.cs):
TypeDescriptor.AddAttributes(typeof(DateOnly), new[] { new TypeConverterAttribute(typeof(DateOnlyConverter)) });
  • use DateOnly as you need for your command-line options
  • when .NET 7 comes out and you upgrade your project to use it, simply delete DateOnlyConverter.cs and the call to TypeDescriptor.AddAttributes

IanKemp avatar Nov 04 '22 17:11 IanKemp