Skip to content

Commit 372d408

Browse files
authored
Add TimeSpan string converter (#1718)
1 parent 689dff5 commit 372d408

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

src/System.CommandLine.Tests/Binding/TypeConversionTests.cs

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -568,6 +568,28 @@ public void Values_can_be_correctly_converted_to_nullable_Guid_without_the_parse
568568
value.Should().Be(Guid.Parse(guidString));
569569
}
570570

571+
[Fact]
572+
public void Values_can_be_correctly_converted_to_TimeSpan_without_the_parser_specifying_a_custom_converter()
573+
{
574+
var timeSpanString = "30";
575+
var option = new Option<TimeSpan>("-x");
576+
577+
var value = option.Parse($"-x {timeSpanString}").GetValueForOption(option);
578+
579+
value.Should().Be(TimeSpan.Parse(timeSpanString));
580+
}
581+
582+
[Fact]
583+
public void Values_can_be_correctly_converted_to_nullable_TimeSpan_without_the_parser_specifying_a_custom_converter()
584+
{
585+
var timeSpanString = "30";
586+
var option = new Option<TimeSpan?>("-x");
587+
588+
var value = option.Parse($"-x {timeSpanString}").GetValueForOption(option);
589+
590+
value.Should().Be(TimeSpan.Parse(timeSpanString));
591+
}
592+
571593
[Fact]
572594
public void Values_can_be_correctly_converted_to_Uri_without_the_parser_specifying_a_custom_converter()
573595
{

src/System.CommandLine/Binding/ArgumentConverter.StringConverters.cs

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -255,5 +255,17 @@ internal static partial class ArgumentConverter
255255
value = default;
256256
return false;
257257
},
258+
259+
[typeof(TimeSpan)] = (string input, out object? value) =>
260+
{
261+
if (TimeSpan.TryParse(input, out var timeSpan))
262+
{
263+
value = timeSpan;
264+
return true;
265+
}
266+
267+
value = default;
268+
return false;
269+
},
258270
};
259271
}

0 commit comments

Comments
 (0)