时间跨度或持续时间格式

时间:2018-08-16 02:38:28

标签: asp.net vb.net time

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

当前,我在数据库中有一条记录,以mmss格式表示时间。例如:5030假设是指50分钟30秒。

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

  • 例如:4020至40m 20s。
  • 例如:6012至1h 12s。
  • 例如:6515至1h 4m 15s。

有什么办法可以实现这一目标? DB内部存储的数据为字符串格式。我目前在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

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

1 个答案:

答案 0 :(得分:1)

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

TimeSpan structure有一个内部机制来计算时间单位,这在这里很有用。所有单位都以天为单位进行转换和度量。如果一个单位的值超过最大值,则会在下一个单位中重新计算。
因此,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 interpolation不可用,请使用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)}"