I am trying to work on Audio file and have seconds as int
in C#, but I would like to convert seconds into hh:mm:ss ( hours, minutes and seconds) format, so How can I do it easily in C#?
For example: 20 Seconds = 00:00:20 in hour,minutes,seconds format.
If you are using .NET 4.0 or above, you can simply convert seconds into TimeSpan and then get hours:minutes:seconds
TimeSpan time = TimeSpan.FromSeconds(seconds);
// backslash is used to ":" colon formatting you will not see it in output
string str = time.ToString(@"hh\:mm\:ss");
Here is the sample Program
using System;
public class Program
{
public static void Main()
{
TimeSpan time = TimeSpan.FromSeconds(890);
// backslash is used to ":" colon formatting you will not see it in output
string str = time .ToString(@"hh\:mm\:ss");
Console.WriteLine(str);
}
}
Output:
00:14:50
You can try it on .NET fiddle: https://dotnetfiddle.net/mMsjxH
If you want to add "miliseconds" also, then use below format
string str = time.ToString(@"hh\:mm\:ss\:fff");
You can also simply use TimeSpan.FromSeconds(90)
where 90 = total number of seconds, this code will convert seconds into hh:mm:ss
Here is the Sample C# Code
using System;
public class Program
{
public static void Main()
{
Console.WriteLine(TimeSpan.FromSeconds(90));
}
}
Output:
00:01:30
Hope it helps, thanks.
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly