Convert duration from 0:00 or 00:00 to 00:00:00
I'm doing up an application that converts the STRING duration of a media file in C#. How do I make it so that the output are as follows:
a. 1:34 (1min 34 sec) to 00:01:34
b. 0:05 (5 seconds) to 00:00:05
c. 1:10:05 to 01:10:05
Result will be displayed in a label named lblDuration.
I am using VS2008 C#.
Thanks if you c开发者_开发知识库an help.
I would parse it as a TimeSpan
, and then reformat it using
string text = timeSpan.ToString("hh':'mm':'ss");
This is assuming you're using .NET 4 with its support for custom TimeSpan
formats. Before .NET 4 you'd have to write it yourself - not too hard, but harder than the above.
Parsing the timespan to start with is a different matter - you could use TimeSpan.TryParseExact
passing in multiple formats, for example.
The benefit of parsing and then reformatting is that you'll validate that you've got sensible date - e.g. not "99:99".
Split the string with a colon (':'), convert each element to a number and print each number using %02d, putting a ':' between 1st and 2nd and 2nd and 3rd
I think the nicest thing to do here is use TimeSpan.TryParse
, BUT we have to be careful - if that method sees an input string with only one :
, it will parse it as hours:minutes
!
(TryParseExact
gets fiddly because no single format accepts both leading zeroes and the absence of leading zeroes).
So:
var input = "5:06";
TimeSpan ts;
var parseSuccessful = TimeSpan.TryParse(input, out ts);
if (parseSuccessful)
{
if (input.Count(c => c == ':') == 1)
{
// TryParse parsed this as hh:mm but we want it to mean mm:ss
// so scale appropriately
ts = new TimeSpan(ts.Ticks / 60);
}
Console.WriteLine(ts.ToString(@"hh\:mm\:ss"));
}
How about parsing it to a DateTime
object then formatting it that way e.g.
DateTime.ParseExact("1:32", 'H:mm', CultureInfo.InvariantCulture).ToString("HH:mm:ss");
Just to clarify - The above solution is a work-around for .NET versions prior to 4 in which you don't have access to custom TimeSpan formats. If you are using .NET 4 then I would definitely recommend using the TimeSpan
as @Jon has suggested
private static string GetLable(string text)
{
if (string.IsNullOrEmpty(text))
return "00:00:00";
var builder = new StringBuilder();
var arr = text.Split(new[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
if (arr.Length == 2)
builder.Append("00:");
var i = 0;
foreach (var t in arr)
{
builder.Append(t.Length == 1 ? "0" + t : t);
if (arr.Length - 1 != i++)
builder.Append(":");
}
return builder.ToString();
}
public void convertString()
{
string str;
str = "your time";
int length = str.Length;
if (length == 4)
{
str = "00" + ":" +"0"+ str;
}
if (length == 5)
{
str = "00" + ":" + str;
}
}
static void Main(string[] args)
{
Program p = new Program();
p.convertString();
}
精彩评论