字符串中日期的转换

时间:2014-07-17 07:56:37

标签: .net vb.net datetime date-format

我想更改字符串的格式,如下例所示。

input : `June 03` output : `2014/06/03`
input : `11-12` output : `2014/12/11`
input : `11-12-2014` output : `2014/12/11`

我最初的尝试是这样的:

 Format(CDate(mskExpDate.Text), "yyyy/MM/dd")

它适用于June 0311-12-2014,但如果我输入11-12,则返回2014/11/12

我在这里做错了什么?

如何让代码适用于所有格式化案例?

3 个答案:

答案 0 :(得分:2)

您可以编写一个函数来尝试解析三种格式的日期,并使用Date.TryParseExact使用custom date and time formats返回可以解析的第一种格式:

Public Function ParseMyDate(dateString As String) As Date
    Dim d As Date
    If Date.TryParseExact(dateString, "MMMM dd", CultureInfo.InvariantCulture, DateTimeStyles.None, d) Then Return d
    If Date.TryParseExact(dateString, "dd-MM", CultureInfo.InvariantCulture, DateTimeStyles.None, d) Then Return d
    If Date.TryParseExact(dateString, "dd-MM-yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, d) Then Return d
    Return Nothing 'you could throw an exception here instead
End Function

用法:

    Dim d1 As Date = ParseMyDate("June 03")
    Dim d2 As Date = ParseMyDate("11-12")
    Dim d3 As Date = ParseMyDate("11-12-2014")

    Debug.WriteLine(d1.ToString("yyyy/MM/dd"))
    Debug.WriteLine(d2.ToString("yyyy/MM/dd"))
    Debug.WriteLine(d3.ToString("yyyy/MM/dd"))

输出:

2014/06/03
2014/12/11
2014/12/11

答案 1 :(得分:0)

你必须创建一些逻辑......然后指定你给出dateparse例程的输入类型(即,月份,日期,年份等......)

DateTime.ParseExact("datestring", "dd/MM/yyyy", Nothing, DateTimeStyles.NoCurrentDateDefault)

答案 2 :(得分:-1)

在我看来,您必须将11-12格式视为一种特殊情况,如下所示:

Private Function ConvertDate(ByVal inputStringDate As String) As Date
    If inputStringDate.split("-").Length = 2 Then
        inputStringDate &= "-" & Now.Year
    End If
    Dim outputDate As Date = Format(CDate(inputStringDate), "yyyy/MM/dd")
    Return outputDate
End Function

测试:

    Dim inputStringDate1 As String = "June 03"
    Dim inputStringDate2 As String = "11-12"
    Dim inputStringDate3 As String = "11-12-2014"

    Dim date1 As Date = ConvertDate(inputStringDate1)
    ' date1 = #6/1/2003#
    Dim date2 As Date = ConvertDate(inputStringDate2)
    ' date2 = #12/11/2014#
    Dim date3 As Date = ConvertDate(inputStringDate3)
    ' date3 = #12/11/2014#