Hai friend i need to convert a string to time format using this code becauseit only support for cloud DB but its not working please dome one help me my duration value is 13:22:00 it is 24 hours format
Group.DurationPerDayAndMactch = TimeSpan.ParseExact(Duration,"hh:mm:ss",CultureInfo.CurrentCulture);
New answer just using TimeSpan
The problem is that :
isn't recognized within the custom TimeSpan
format specifier. You need to escape it. At that point, the culture really isn't relevant at all, so I'd specify the invariant culture, personally:
TimeSpan result = TimeSpan.ParseExact(input, "hh':'mm':'ss",
CultureInfo.InvariantCulture);
Personally I find it irritating that :
isn't recognized... but that's a matter for the BCL team.
Original answer
Personally I'd use my Noda Time library, which aims to be a generally better date/time library for .NET. You can then parse it as a Duration
, and convert that to a TimeSpan
if you need to:
using System;
using NodaTime;
using NodaTime.Text;
class Test
{
static void Main()
{
string input = "13:12:34";
DurationPattern pattern =
DurationPattern.CreateWithInvariantCulture("H:mm:ss");
// TODO: Consider error handling. The ParseResult<T> returned by
// pattern.Parse helps with that.
Duration duration = pattern.Parse(input).Value;
TimeSpan timeSpan = duration.ToTimeSpan();
Console.WriteLine(timeSpan);
}
}
(Alternatively, you could just store the number of ticks in the duration.)
Note that I've used the invariant culture here - that's usually more appropriate when you're specifying an exact pattern.
You could use the current culture, but it would only affect the time separator (:
in the invariant culture) in the pattern you're providing.
See more on this question at Stackoverflow