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
Patricia ArquetteOriginal
2025-01-07 09:41:44268browse

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);

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");

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!

Statement:
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