首页 > 解决方案 > 时间跨度或持续时间格式

问题描述

我有 1 个关于时间跨度/持续时间管理的问题。

目前,我在数据库中有一条以mmss格式表示时间的记录。示例:5030 表示 50 分 30 秒。

我想以这种格式在我的网页上显示它:

有什么办法可以做到这一点吗?存储在数据库中的数据是字符串格式的。我目前在 ASP.NET 应用程序中使用 VB.NET 语言。

我在整个互联网上进行了搜索,但我不断得到代表时间的结果,而不是持续时间。

目前,我正在这样做,但我仍然无法显示小时:

If arrayValueInside.Length > 0 Then
    If arrayValueInside(0) = "STOPPING TIME" Then
        Dim strTime As String = arrayValueInside(1).Trim()
        Select Case strTime.Length
            Case 1
                strTime = strTime & "s"
            Case 2
                strTime = strTime & "s"
            Case 3
                strTime = strTime.Substring(0, 1) & "m " & strTime.Substring(1, 2) & "s"
            Case 4
                strTime = strTime.Substring(0, 2) & "m " & strTime.Substring(2, 2) & "s"
            '   If Integer.Parse(strTime) >= 6000 Then
            '       Return strTime.Substring(0, 2) + "m" + strTime.Substring(1, 2) + "s"
            '   Else
            '   End If
            Case 5
                strTime = strTime.Substring(0, 3) & "m " & strTime.Substring(3, 2) & "s"
        End Select

如果我提供的信息中有任何不清楚的地方,请告诉我。

标签: asp.netvb.nettime

解决方案


由于时间格式以 形式呈现mmss,我认为还应该考虑分钟值,在某些情况下,可能会超过"99"并可以用 3 个(或更多)数字表示。

TimeSpan 结构有一个内部机制来计算时间单位,这在这里很有用。所有单位都以天为单位进行调换和测量。如果一个单位的值超过它的最大值,它将在下一个单位中重新计算。
因此,70 分钟将变为 1 小时 10 分钟。

这里,最右边的2个字符被认为代表秒值;所有其他(2 个或更多)代表分钟。

Dim input As String = "12845"
Dim seconds As Integer = Integer.Parse(input.Substring(input.Length - 2, 2))
Dim minutes As Integer = Integer.Parse(input.Substring(0, input.Length - 2))
Dim ts As New TimeSpan(0, 0, minutes, seconds)

Dim TimeFormat = $"{ts.Hours}h {ts.Minutes}m {ts.Seconds}s"

TimeFormat 字符串将为2h 8m 45s.

如果字符串插值不可用,请使用String.Format()方法:

Dim TimeFormat = String.Format("{0}h {1}m {2}s", ts.Hours, ts.Minutes, ts.Seconds)


稍作修改的方法,如果单位值为 0,则不返回单位度量值。如果
输入字符串为"12045",则先前的方法将返回2h 0m 45s。这个会回来2h 45s的。

Dim TimeFormat As String() = New String() {
    (If(ts.Hours > 0, ts.Hours & "h", "")),
    (If(ts.Minutes > 0, " " & ts.Minutes & "m", "")),
    (If(ts.Seconds > 0, " " & ts.Seconds & "s", ""))
}

Dim output As String = $"{TimeFormat(0)}{TimeFormat(1)}{TimeFormat(2)}"

推荐阅读