Search code examples
c#timemilliseconds

Convert any time format in milliseconds with C#


I have a time in this format: 00:02:13,512 Is there a method in C# that can convert this time to milliseconds (and vice versa) or must i do it manually?


Solution

  • Use TimeSpan to store this information. You can use TimeSpan.ParseExact like:

    TimeSpan ts = TimeSpan.ParseExact("00:02:13,512", 
                                      @"hh\:mm\:ss\,fff", 
                                      CultureInfo.InvariantCulture);
    

    You can get TotalMilliseconds using TimeSpan.TotalMilliseconds property:

    var totlaMilliseconds = ts.TotalMilliseconds;
    

    This would give you back 133512.0 if you just need to Millisecond part then you can use ts.Milliseconds; which would give you 512