Description
Background and motivation
A lot of tools that work with time strings (e.g. FFmpeg), as well as data formats (e.g. SRT), use the following format for consuming and rendering timestamps:
hh:mm:ss.fff
This is pretty similar to .NET's built-in c
format, except that the latter has a component for days too:
[d.]hh:mm:ss.fff
It would be incredibly convenient to have a separate built-in format that works exactly like c
, but instead of rendering days, it should just render the total number of hours, even if they exceed a full day.
Because there is no formatting token for rendering hours beyond 24, currently the only workaround is to do something like this:
var value = TimeSpan.FromHours(27.123);
var str =
Math.Floor(value.TotalHours).ToString("00") + ':' +
value.Minutes.ToString("00") + ':' +
value.Seconds.ToString("00") + '.' +
value.Milliseconds.ToString("000");
This is pretty cumbersome. You can, of course, create an extension method to clean it up here, but that wouldn't work so well in the equivalent parsing scenario:
var str = "27:07:22.680";
var match = Regex.Match(str, @"(\d\d):(\d\d):(\d\d\.\d+)");
if (match.Success)
{
var hours = int.Parse(totalDurationMatch.Groups[1].Value, CultureInfo.InvariantCulture);
var minutes = int.Parse(totalDurationMatch.Groups[2].Value, CultureInfo.InvariantCulture);
var seconds = double.Parse(totalDurationMatch.Groups[3].Value, CultureInfo.InvariantCulture);
var value =
TimeSpan.FromHours(hours) +
TimeSpan.FromMinutes(minutes) +
TimeSpan.FromSeconds(seconds);
}
API Proposal
I suggest adding a new standard format, for example ch
C
(I don't really care how it's called):
var value = TimeSpan.FromHours(27.123);
var str = value.ToString("C"); // 27:07:22.680
It should also be supported in TimeSpan.ParseExact(...)
and related methods:
var str = "27:07:22.680";
var value = TimeSpan.ParseExact(str, "C", null);
// { Days: 1, Hours: 3, Minutes: 7, Seconds: 22, Milliseconds: 680 }
API Usage
See above
Alternative Designs
No response
Risks
No response