Home > Backend Development > C#.Net Tutorial > 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
Release: 2023-09-01 22:45:02
forward
1587 people have browsed it

在 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();
}
Copy after login

Output

01h:02m:32s:000ms
Copy after login

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();
}
Copy after login

Output

00h:00m:06s:000ms
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template