[英]Convert SQL Date time format to String
when reading SQl Date time field , only i can take the date with time ..how to get only date in to text box from Ajax or some method. 当阅读SQl日期时间字段时,只有我可以带日期的日期..如何从Ajax或某些方法仅将日期输入文本框。
this is what i need to do 这是我需要做的
http://i.stack.imgur.com/n0fgG.jpg http://i.stack.imgur.com/n0fgG.jpg
that's how I'm taking the date to text box. 这就是我将日期带到文本框中的方式。
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();
}
}
Don't convert the raw value to a string
in the first place - it should already be a DateTime: 首先不要将原始值转换为string
-它应该已经是DateTime了:
DateTime date = (DateTime) dsr["ExpireDate"];
Then you can convert it into whatever format you're interested in: 然后,您可以将其转换为您感兴趣的任何格式:
// TODO: Consider specifying the culture too, or specify a standard pattern.
tHFExpiaryDate.Text = date.ToString("MM/d/yyyy");
It's important to separate the question of "How can I get the data from the database in an appropriate type?" 分开“如何从合适的类型的数据库中获取数据的问题”这一问题很重要。 from "How should I present the data to the user?" 来自“我应该如何向用户展示数据?”
Try something like: 尝试类似:
DateTime.ParseExact(sdr["ExpireDate"].ToString(), "MM/d/yyyy", CultureInfo.InvariantCulture)
In your sample: 在您的示例中:
tHFExpiaryDate.Text = DateTime.ParseExact( ((DateTime)dt.Rows[0][0]).ToString("MM/d/yyyy"), "MM/d/yyyy", System.Globalization.CultureInfo.CurrentCulture).ToString("MM/d/yyyy"));
This always works for me 这总是对我有用
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;
}
Other date format example http://www.dotnetperls.com/datetime-format 其他日期格式示例http://www.dotnetperls.com/datetime-format
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.