I am working on a .NET Core MVC app that takes a user's run data as input and stores it in a database. The user will input a Time (total time of run), Pace (per mile), and Distance (in miles) and then submit. Both Time and Pace are TimeSpan's.
Here is where my problem comes up:
Example: If I want to enter in 45 mins and 15 seconds for Time, the user has to enter in 00:45:15
, which they aren't going to do. If they were to enter in 45:15
, it would show up in the DB as 45 hours 15 minutes - which is obviously not what we want.
My question is, what would be the best way to format this so that when a user enters in this format XX:XX
it stores the run as minutes:seconds, but if a user enters in XX:XX:XX
(for runs over an hour) it stores as hours:minutes:seconds?
Thanks in advance!
How about one size fits all
foreach (var s in new[] {"00:45:15", "45:15" })
{
var parsed = TimeSpan.TryParseExact(s, new[] { "mm\\:ss", "hh\\:mm\\:ss" }, null, out var result);
Assert.IsTrue(parsed);
Assert.AreEqual(0, result.Hours);
Assert.AreEqual(45, result.Minutes);
Assert.AreEqual(15, result.Seconds);
}