What is the best way to convert seconds into (Hour:Minutes:Seconds:Milliseconds) time in C#?


DateTime

DateTime is a structure of value Type like int, double etc. It is available in System namespace and present in mscorlib.dll assembly.It implements interfaces like IComparable, IFormattable, IConvertible, ISerializable, IComparable, IEquatable.DateTime contains properties like Day, Month, Year, Hour, Minute, Second, DayOfWeek and others in a DateTime object.

TimeSpan

TimeSpan struct represents a time interval that is difference between two times measured in number of days, hours, minutes, and seconds.TimeSpan is used to compare two DateTime objects to find the difference between two dates. TimeSpan class provides FromDays, FromHours, FromMinutes, FromSeconds, and FromMilliseconds methods to create TimeSpan objects from days, hours, minutes, seconds, and milliseconds respectively.

Example 1

static void Main(string[] args){
   TimeSpan t = TimeSpan.FromSeconds(3752);
   string answer = string.Format("{0:D2}h:{1:D2}m:{2:D2}s:{3:D3}ms",
   t.Hours,
   t.Minutes,
   t.Seconds,
   t.Milliseconds);
   System.Console.WriteLine(answer);
   Console.ReadLine();
}

Output

01h:02m:32s:000ms

Example 2

static void Main(string[] args){
   TimeSpan t = TimeSpan.FromSeconds(6);
   string answer = string.Format("{0:D2}h:{1:D2}m:{2:D2}s:{3:D3}ms",
   t.Hours,
   t.Minutes,
   t.Seconds,
   t.Milliseconds);
   System.Console.WriteLine(answer);
   Console.ReadLine();
}

Output

00h:00m:06s:000ms

Updated on: 07-Nov-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements