Skip to main content
 首页 » 编程设计

c#之SQL Server 2008 DATE 类型在 visual studio 中显示 DATE & TIME

2024年02月23日17rubylouvre

我正在使用 SQL Server 2008,我的字段有 DATE 类型,但是在我程序的 Visual Studio 中,当我读取可能的数据时,它会显示 DATE & TIME 应该是什么我愿意?我尝试在我的程序的 SELECT 查询中转换我的字段,但它给了我一些错误,我该如何解决这个问题?

这是我的后台代码:

     protected void Page_Load(object sender, EventArgs e) 
        { 
                SqlCommand cmd = new SqlCommand(); 
                cmd.Connection = new SqlConnection(Class1.CnnStr); 
                SqlDataReader reader; 
 
 
                cmd.CommandText = "select ContractStartDate,MandateValidDate from table where BrokerName=@BrokerName"; 
                cmd.Connection.Open(); 
                cmd.Parameters.AddWithValue("@BrokerName", BrokerName_txt.Text); 
                reader = cmd.ExecuteReader(); 
 
                if (reader.Read()) 
                { 
 
 
                    ContractStartDate_txt.Text = Convert.ToDateTime(reader["ContractStartDate"]).ToString("dd/MM/yyyy"); 
                    MandateValidDate_txt.Text = Convert.ToDateTime(reader["MandateValidDate"]).ToString("dd/MM/yyyy");                
                    reader.Close(); 
                } 
                cmd.Connection.Close(); 
 
            } 

因为我想在读取数据后保存数据,所以出现错误:

Conversion failed when converting date and/or time from character string.

请您参考如下方法:

您使用 Convert.ToDateTime()首先转换从数据库返回的字符串,然后使用 DateTime.ToString("dd/MM/yyyy")您只能从日期和时间中获取日期值。

ContractStartDate_txt.Text = Convert.ToDateTime(reader["ContractStartDate"]).ToString("dd/MM/yyyy"); 
MandateValidDate_txt.Text = Convert.ToDateTime(reader["MandateValidDate"]).ToString("dd/MM/yyyy");