Skip to content

Add TimeSpan string converter #1718

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions src/System.CommandLine.Tests/Binding/TypeConversionTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -568,6 +568,28 @@ public void Values_can_be_correctly_converted_to_nullable_Guid_without_the_parse
value.Should().Be(Guid.Parse(guidString));
}

[Fact]
public void Values_can_be_correctly_converted_to_TimeSpan_without_the_parser_specifying_a_custom_converter()
{
var timeSpanString = "30";
var option = new Option<TimeSpan>("-x");

var value = option.Parse($"-x {timeSpanString}").GetValueForOption(option);

value.Should().Be(TimeSpan.Parse(timeSpanString));
}

[Fact]
public void Values_can_be_correctly_converted_to_nullable_TimeSpan_without_the_parser_specifying_a_custom_converter()
{
var timeSpanString = "30";
var option = new Option<TimeSpan?>("-x");

var value = option.Parse($"-x {timeSpanString}").GetValueForOption(option);

value.Should().Be(TimeSpan.Parse(timeSpanString));
}

[Fact]
public void Values_can_be_correctly_converted_to_Uri_without_the_parser_specifying_a_custom_converter()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -255,5 +255,17 @@ internal static partial class ArgumentConverter
value = default;
return false;
},

[typeof(TimeSpan)] = (string input, out object? value) =>
{
if (TimeSpan.TryParse(input, out var timeSpan))
{
value = timeSpan;
return true;
}

value = default;
return false;
},
};
}