代码之家  ›  专栏  ›  技术社区  ›  Etienne

更改数据库中日期字段的日期格式

  •  1
  • Etienne  · 技术社区  · 15 年前

    我正在将ASP.NET与SQL Server 2005结合使用。

    我的日期保存在数据库中,数据类型为“smalldatetime”。

    我正在将日期值显示在一个名为txtdate的文本框中,其中有一个阅读器……

        Dim conn As Data.SqlClient.SqlConnection
        Dim Comm As Data.SqlClient.SqlCommand
        Dim reader As Data.SqlClient.SqlDataReader
    
        conn = New Data.SqlClient.SqlConnection(..............)
    
        Comm = New Data.SqlClient.SqlCommand( _
        ("SELECT * FROM Table1 WHERE Age = 88"), conn)
    
        conn.Open()
    
        reader = Comm.ExecuteReader()
    
        If reader.Read() Then
    
            txtDate.Text = reader.Item("theDate").ToString
    
        End If
    
        reader.Close()
        conn.Close()
    

    但目前我的日期显示为“2008/06/30 12:00:00 am”,我想显示为“2008年6月30日”。

    怎么能做到?

    3 回复  |  直到 15 年前
        1
  •  1
  •   Jon Skeet    15 年前

    如何将数据存储在数据库中无关紧要-您将获得 DateTime 回到您的客户机代码中。然后您只需要格式化您想要的格式。

    尝试如下操作:

    If reader.Read() Then
        Dim date as DateTime = CType(reader.Item("theDate"), DateTime)
        txtDate.Text = date.ToString("dd MMMM yyyy")
    End If
    

    在这里,“dd”表示“月日”,“mmmm”表示“一年中的月份”和“yyyy”表示“四位数的年份”。

    MSDN on custom date and time format strings 了解更多详细信息。或者,您可以使用 standard date and time format string 考虑到你现在的文化。(自定义字段将考虑每个单独字段的设置,因此月份名称将适合区域性,但要设置格式的字段的顺序和样式由格式字符串固定。)

        2
  •  2
  •   David M    15 年前

    替换 ToString 具有 ToString("dd MMMM yyyy") . 您可能需要在msdn中查看date time.toString的重载,以及日期时间格式化字符串。

    代码中的其他点-如果确实要从一行中选择一个值,则限制选择列表(即不要使用 SELECT * )考虑使用executescalar而不是executereader…

        3
  •  0
  •   Adriaan Stander    15 年前

    您应该使用数据格式来字符串。

    发挥你的价值 读卡器项目(“日期”)。 并使用ToString方法。

    yourDateTime.ToString("dd MMMM yyyy");
    

    看看这些