字符串未被识别为有效的日期时间

时间:2014-01-21 11:18:08

标签: vb.net sql-server-2008 datetime

我试图将用户的生日显示为“1990年1月1日” - “MMMM dd,yyyy” 来自我的数据库

我数据库中的数据类型是DateTime,格式为“yyyy-MM-dd hh:mm:ss”

但每当我试图展示它时。它会收到错误“字符串未被识别为有效的日期时间”

  Try
        con.Open()
        ListView1.Items.Clear()
        comm.CommandText = "SELECT user_id, last_name + ', ' + first_name + ' ' + middle_name as name, course, section, position, address, birthday from Users"
        comm.Connection = con
        dr = comm.ExecuteReader
        While (dr.Read())
            Dim mydate = (dr("birthday"))
            Dim edate As Date = Date.ParseExact(mydate, "MMMM/dd/yyyy", System.Globalization.DateTimeFormatInfo.InvariantInfo)
            With ListView1.Items.Add(dr("user_id"))
                .subItems.Add(dr("name"))
                .subItems.Add(dr("course"))
                .subItems.Add(dr("section"))
                .subItems.Add(dr("position"))
                .subItems.Add(dr("address"))
                .subItems.Add(edate)
            End With
        End While
        comm.Dispose()
        dr.Close()
        con.Close()
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try

1 个答案:

答案 0 :(得分:0)

如果你想要这种格式' 1993年1月1日' ...试试这个......

Try
    con.Open()
    ListView1.Items.Clear()
    comm.CommandText = "SELECT user_id, last_name + ', ' + first_name + ' ' + middle_name as name, course, section, position, address, birthday from Users"
    comm.Connection = con
    dr = comm.ExecuteReader
    While (dr.Read())
        Dim mydate = (dr("birthday"))
        Dim edate As Date = mydate
        With ListView1.Items.Add(dr("user_id"))
            .subItems.Add(dr("name"))
            .subItems.Add(dr("course"))
            .subItems.Add(dr("section"))
            .subItems.Add(dr("position"))
            .subItems.Add(dr("address"))
            .subItems.Add(Format(edate, "MMMM d,yyyy"))
        End With
    End While
    comm.Dispose()
    dr.Close()
    con.Close()
Catch ex As Exception
    MsgBox(ex.Message)
End Try