Home > Backend Development > C++ > How Can I Convert Seconds to HH:MM:SS:fff Format in .NET?

How Can I Convert Seconds to HH:MM:SS:fff Format in .NET?

Patricia Arquette
Release: 2025-01-07 09:41:44
Original
291 people have browsed it

How Can I Convert Seconds to HH:MM:SS:fff Format in .NET?

Converting Seconds to (Hour:Minutes:Seconds:Milliseconds) Format

When working with time-related calculations in .NET, you may encounter the need to convert seconds into a human-readable (Hour:Minutes:Seconds:Milliseconds) format.

SOLUTION:

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:

  • Leverage the TimeSpan class with the custom format string:

    TimeSpan time = TimeSpan.FromSeconds(seconds);
    
    // Backslash is necessary to escape the colon character
    string str = time.ToString(@"hh\:mm\:ss\:fff");
    Copy after login

Caution:

  • Ensure that the input value seconds is within the bounds of TimeSpan.MaxValue.TotalSeconds to avoid exceptions.

The above is the detailed content of How Can I Convert Seconds to HH:MM:SS:fff 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template