Search code examples
c#wpfvb.netdatetimestring-formatting

Timeformat that show total elapsed minutes


I wanted to give the user the option to choose the format in which a timer is displayed. The timeformats a user kan choose:

mm\:ss
mm\:ss\.f
mm\:ss\.ff
hh\:mm\:ss
hh\:mm\:ss\.f
hh\:mm\:ss\.ff

Then in code i have a timespan that is converted to String like:

Return timespan.ToString(TimeFormat)

The thing is that if a user uses the format mm:ss then the Minutes are showed and when it elapse 59 minutes it starts at zero again. What i would like is to display the total minutes. So 60minutes43seconds

I've read the whole MS documentation but can't find a solution for this. https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-date-and-time-format-strings


Solution

  • With the advice i got from the comments and some more googling i dind't find a very framework like solution so i inded up with a dirty Select Case that works like a charm.

    Select Case objSettings.TimeFormat
        Case "m\:ss"
            Return String.Format("{0}:{1:00}", Math.Floor(time.TotalMinutes), time.Seconds)
        Case "m\:ss\.f"
            Return String.Format("{0}:{1}", Math.Floor(time.TotalMinutes), time.ToString("ss\.f"))
        Case "m\:ss\.ff"
            Return String.Format("{0}:{1}", Math.Floor(time.TotalMinutes), time.ToString("ss\.ff"))
        Case "mm\:ss"
            Return String.Format("{0:0#}:{1:00}", Math.Floor(time.TotalMinutes), time.Seconds)
        Case "mm\:ss\.f"
            Return String.Format("{0:0#}:{1:00}", Math.Floor(time.TotalMinutes), time.ToString("ss\.f"))
        Case "mm\:ss\.ff"
            Return String.Format("{0:0#}:{1:00}", Math.Floor(time.TotalMinutes), time.ToString("ss\.ff"))
        Case "hh\:mm\:ss"
            Return String.Format("{0:0#}:{1}", Math.Floor(time.TotalHours), time.ToString("mm\:ss"))
        Case "hh\:mm\:ss\.f"
            Return String.Format("{0:0#}:{1}", Math.Floor(time.TotalHours), time.ToString("mm\:ss\.f"))
        Case "hh\:mm\:ss\.ff"
            Return String.Format("{0:0#}:{1}", Math.Floor(time.TotalHours), time.ToString("mm\:ss\.ff"))
        Case Else
            Return time.ToString(objSettings.TimeFormat)
    End Select