How to convert seconds into hh:mm:ss in C#?


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.


Asked by:- bhanu
0
: 7297 At:- 4/1/2021 1:56:02 PM
C# datetime format







2 Answers
profileImage Answered by:- vikas_jk

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");
2
At:- 4/1/2021 2:13:42 PM
Excellent, thanks for quick answer, fiddle helps. 0
By : bhanu - at :- 4/1/2021 2:14:58 PM


profileImage Answered by:- neena

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.

0
At:- 11/25/2021 3:23:10 PM






Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use