将 SQL 日期时间格式转换为字符串
本文关键字:转换 字符串 格式 时间 SQL 日期 | 更新日期: 2023-09-27 18:33:38
读取SQl日期时间字段时,只有我才能获取带有时间的日期..如何从Ajax或某些方法仅获取日期到文本框。
这是我需要做的
https://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();
}
}
首先不要将原始值转换为string
- 它应该已经是一个日期时间:
DateTime date = (DateTime) dsr["ExpireDate"];
然后,您可以将其转换为您感兴趣的任何格式:
// TODO: Consider specifying the culture too, or specify a standard pattern.
tHFExpiaryDate.Text = date.ToString("MM/d/yyyy");
将"如何从数据库中获取适当类型的数据?"与"我应该如何向用户呈现数据"的问题分开非常重要
尝试类似操作:
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"));
这总是对我有用
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;
}
其他日期格式示例 http://www.dotnetperls.com/datetime-format