Home > Backend Development > C++ > How to Convert Seconds to HH:MM:SS:FFF Time Format in .NET?

How to Convert Seconds to HH:MM:SS:FFF Time Format in .NET?

DDD
Release: 2025-01-07 09:36:41
Original
204 people have browsed it

How to Convert Seconds to HH:MM:SS:FFF Time Format in .NET?

Convert Seconds into (Hour:Minutes:Seconds:Milliseconds) Time

To convert seconds into a formatted time string, consider the following solutions:

For .NET <= 4.0:

Utilize the TimeSpan class:

TimeSpan t = TimeSpan.FromSeconds(secs);

string answer = string.Format("{0:D2}h:{1:D2}m:{2:D2}s:{3:D3}ms", 
                t.Hours, 
                t.Minutes, 
                t.Seconds, 
                t.Milliseconds);
Copy after login

For .NET > 4.0:

Use the TimeSpan class with a custom format string:

TimeSpan time = TimeSpan.FromSeconds(seconds);

// backslash is essential to indicate that colon is not part of the format
string str = time.ToString(@"hh\:mm\:ss\:fff");
Copy after login

Important Notes:

  • Ensure that the seconds value is less than the maximum allowed value for TimeSpan (TimeSpan.MaxValue.TotalSeconds) to prevent an exception.
  • The format string can be customized to meet specific requirements, such as omitting hours if they are zero.

The above is the detailed content of How to Convert Seconds to HH:MM:SS:FFF Time Format in .NET?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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