Home > Backend Development > C++ > How Do I Convert Seconds to a Formatted Time Duration (hh:mm:ss:fff) in .NET?

How Do I Convert Seconds to a Formatted Time Duration (hh:mm:ss:fff) in .NET?

Mary-Kate Olsen
Release: 2025-01-07 09:51:40
Original
259 people have browsed it

How Do I Convert Seconds to a Formatted Time Duration (hh:mm:ss:fff) in .NET?

Converting Seconds to Time Duration

In .NET, you can convert seconds into a formatted time duration, such as "00h:00m:00s:00ms." Here's how you can achieve this:

For .NET <= 4.0:

The TimeSpan class provides a convenient way to represent time durations. To convert seconds into a TimeSpan object:

TimeSpan t = TimeSpan.FromSeconds(seconds);
Copy after login

To format the TimeSpan in the desired format, use the "string.Format" method:

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

This will produce a formatted string with the specified placeholders filled with the corresponding values from the TimeSpan object.

For .NET > 4.0:

In .NET 4.0 and above, you can also use the ToString() method of TimeSpan with a custom format string to achieve the desired result:

TimeSpan time = TimeSpan.FromSeconds(seconds);

// Use backslash to escape the colon character
string str = time.ToString(@"hh\:mm\:ss\:fff");
Copy after login

Additional Note:

As mentioned in the provided answer, ensure that the input seconds value is less than the maximum allowed value for TimeSpan.MaxValue.TotalSeconds (approximately 24 days) to avoid an exception.

The above is the detailed content of How Do I Convert Seconds to a Formatted Time Duration (hh:mm:ss:fff) 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template