我只需要从SQL获取日期部分。 SQL数据类型是日期,但是当我尝试调用它时,它返回此值01-Mar-14 12:00:00 AM
。我感兴趣的唯一部分是01-Mar-14
我在stackoverflow和微软以及google中进行了长时间的搜索但是徒劳无功。
First search didn't work with me
also this one didn't work out
这是我的C#代码来获取这些值。
private void SearchName_Click(object sender, EventArgs e)
{
db.con.Open();
SqlDataReader reader;
SqlCommand command = new SqlCommand("select * from Employee inner join DatePics on ID=Emp_ID where EmpName='" + SearNametxt.Text + "' ", db.con);
reader = command.ExecuteReader();
while (reader.Read())
{
NameSeartxt.Text = (reader["EmpName"].ToString());
PassSeartxt.Text = (reader["Passport"].ToString());
IDSeartxt.Text = (reader["IDIssue"].ToString());
expiryseartxt.Text = (reader["IDExpiry"].ToString());
}
db.con.Close();
}
但也只返回整个格式。试图使用这个,但失败了
select convert(varchar(10), '01-Mar-14 12:00:00', 120)
编辑:最新代码:
db.con.Open();
SqlDataReader reader;
SqlCommand command = new SqlCommand("select * from Employee inner join
DatePics on ID=Emp_ID where EmpName='" + SearNametxt.Text + "' ", db.con);
reader = command.ExecuteReader();
while (reader.Read())
{
DateTime Received;
DateTime.TryParse(reader["ReceivedDate"], CultureInfo.InvariantCulture,
DateTimeStyles.None, out Received);
recsearchtxt.Text = Received.ToString("d");
答案 0 :(得分:3)
您需要将第一个参数作为String传递,因此使用reader["ReceivedDate"]
将reader["ReceivedDate"].ToString()
转换为字符串
试试这个:
DateTime Received;
DateTime.TryParse(reader["ReceivedDate"].ToString(),
CultureInfo.InvariantCulture, DateTimeStyles.None, out Received);
答案 1 :(得分:2)
您应该可以执行以下操作:
DateTime issueDate;
DateTime.TryParse(reader["IDIssue"].ToString(), out issueDate);
IDSeartxt.Text = issueDate.ToString("d");
虽然您需要使用正确的格式化参数。
这是fiddle。
答案 2 :(得分:1)
要获取日期,请使用convert()
格式规范:
select *, convert(varchar(10), datecol, 121) as datestr
from Employee inner join
DatePics
on ID = Emp_ID
where EmpName='" + SearNametxt.Text + "' ";
这会将其转换为YYYY-MM-DD。
答案 3 :(得分:0)
尝试:
expiryseartxt.Text = (reader["IDExpiry"].ToShortDateString());
或者这个:
expiryseartxt.Text = reader.GetDateTime().ToShortDateString();