当读取SQl日期时间字段时,只有我可以将日期与时间相关...如何从Ajax或某种方法获取文本框中的日期。
这就是我需要做的事情
http://i.stack.imgur.com/n0fgG.jpg
这就是我把日期带到文本框的方式。
protected void ddlBatch_SelectedIndexChanged(object sender, EventArgs e)
{
String strConnString = ConfigurationManager.ConnectionStrings["CBConnectionString"].ConnectionString;
const String strQuery = "select ItemIdentityCode, Qty, PurchasingPrice, ExpireDate, DiscountRate, IssueMode, Principle, Force from DEL_PurchasesLines where BatchNumber = @BatchNumber";
SqlConnection conPR = new SqlConnection(strConnString);
SqlCommand cmdPR = new SqlCommand();
cmdPR.Parameters.AddWithValue("@BatchNumber", ddlBatch.SelectedItem.Value);
cmdPR.CommandType = CommandType.Text;
cmdPR.CommandText = strQuery;
cmdPR.Connection = conPR;
try
{
conPR.Open();
SqlDataReader sdr = cmdPR.ExecuteReader();
while (sdr.Read())
{
tHFExpiaryDate.Text = sdr["ExpireDate"].ToString();
}
}
catch (Exception ex)
{
//throw ex;
}
finally
{
conPR.Close();
conPR.Dispose();
}
}
答案 0 :(得分:9)
首先不要将原始值转换为string
- 它应该已经是DateTime:
DateTime date = (DateTime) dsr["ExpireDate"];
然后您可以将其转换为您感兴趣的任何格式:
// TODO: Consider specifying the culture too, or specify a standard pattern.
tHFExpiaryDate.Text = date.ToString("MM/d/yyyy");
将“如何以适当的类型从数据库中获取数据?”这一问题分开是很重要的。来自“我应该如何向用户提供数据?”
答案 1 :(得分:1)
尝试类似:
DateTime.ParseExact(sdr["ExpireDate"].ToString(), "MM/d/yyyy", CultureInfo.InvariantCulture)
在您的样本中:
tHFExpiaryDate.Text = DateTime.ParseExact( ((DateTime)dt.Rows[0][0]).ToString("MM/d/yyyy"), "MM/d/yyyy", System.Globalization.CultureInfo.CurrentCulture).ToString("MM/d/yyyy"));
答案 2 :(得分:0)
这总是对我有用
protected String getDate(string date)
{
DateTime dDate;
string sdate = null;
if (!string.IsNullOrEmpty(date.ToString()))
{
dDate = DateTime.Parse(date.ToString());
sdate = dDate.ToString("dd/MM/yyyy");
sdate = dDate.ToLongDateString();
}
return sdate;
}