Home  >  Article  >  Backend Development  >  What is the best way to convert seconds to (hours:minutes:seconds:milliseconds) time in C#?

What is the best way to convert seconds to (hours:minutes:seconds:milliseconds) time in C#?

PHPz
PHPzforward
2023-09-01 22:45:021516browse

在 C# 中将秒转换为(小时:分钟:秒:毫秒)时间的最佳方法是什么?

DateTime

DateTime is a value type structure, similar to int, double, etc. It is available in the System namespace and is present in the mscorlib.dll assembly. It implements interfaces such as IComparable, IFormattable, IConvertible, ISerializable, IComparable, and IEquatable. DateTime contains Day, Month, Year, Hour, Minute, Second, DayOfWeek and other attributes in a DateTime object.

TimeSpan

The TimeSpan structure represents the time interval between two times, expressed in days, hours, minutes and seconds. TimeSpan is used to compare two DateTime objects to find the difference between two dates. The TimeSpan class provides FromDays, FromHours, FromMinutes, FromSeconds and FromMilliseconds methods for creating 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

The Chinese translation of Example 2

is:

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

The above is the detailed content of What is the best way to convert seconds to (hours:minutes:seconds:milliseconds) time in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete
Previous article:Chained exceptions in C#Next article:Chained exceptions in C#