问题描述
我正在尝试从数据库中读取 date
字段并将其设置为标签字段.我正在使用以下代码,
I am trying to read a date
field from database and set it to a label field. Im using the following code,
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("select BirthDate from Student where Name=@name", con);
cmd.Parameters.AddWithValue("@name", "Mano");
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
lblName.Text = dt.Rows[0]["Date"].ToString();
但是这会以 02-05-1991 00:00:00
的格式在标签中显示数据值,但是我想以 dd-mm-yyyy
作为 05-02-1991
.所以我尝试了以下代码:
But this displays the data value in label in the format 02-05-1991 00:00:00
but I want to display it in format dd-mm-yyyy
as 05-02-1991
. So I tried the following code:
lblName.Text = dt.Rows[0]["BirthDate"].ToString("dd-mm-yyyy");
但它显示此错误:
如何更改格式?
推荐答案
假设 BirthDate
表示有效的 DateTime
,请在调用 ToString()之前进行转换代码>.
Assuming BirthDate
represents a valid DateTime
, convert it before calling ToString()
.
lblName.Text = Convert.ToDateTime(dt.Rows[0]["BirthDate"]).ToString("dd-mm-yyyy");
您当前正在对象类上调用 ToString()
方法,而不是 DateTime
类,因此没有允许日期格式化程序的重载.
You're currently calling the ToString()
method on the object class, not the DateTime
class, so there's no overload that allows for a date formatter.
这篇关于从数据库读取并设置为标签时,更改C#中的日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!