将表示24小时的字符串转换为12小时的VB.NET

时间:2009-03-26 18:50:23

标签: vb.net datetime

感谢casperOne's answer,这是我的结果函数:

Shared Function FormatDate(ByVal s As String) As String
    Dim DT As DateTime
    s = Regex.Replace(s, "[^1234567890]", "")
    DT = DateTime.ParseExact(s, "HHmm", _
        Globalization.CultureInfo.InvariantCulture)
    Return DT.ToString("h:mm tt")
End Function

我正在读取一个以字符串格式保存时间信息的数据库,hh:mm。出于某种原因,我记得我很久以前用过的内置函数,但是对于我的生活,我不记得怎么做了。所以相反,我写了这个快速的脏函数:

 Shared Function FormatDate(ByVal s As String) As String
    '' this function takes a time string from the database
    '' and changes it from 24h to 12h

    Dim oSplit As String() = s.Split(":"c)
    Dim oRet As String = "", suffix As String = ""
    Dim hour, minute As String

    If CInt(oSplit(0)) > 12 Then
        hour = CStr(CInt(oSplit(0)) - 12)
        suffix = "PM"
    Else
        hour = oSplit(0)
        suffix = "AM"
    End If
    minute = oSplit(1)
    oRet = String.Format("{0}:{1} {2}", hour, minute, suffix)
    Return oRet
End Function

有谁知道我认为我所指的特定功能?

1 个答案:

答案 0 :(得分:5)

你可以看到答案发布在“如何转换1400-1500到下午2点 - 下午3点?”的问题,位于:

How to convert 1400-1500 to 2pm - 3pm?

在格式中,您将格式为小写h的大写字母H替换为12小时格式。