簡體   English   中英

將SQL日期時間格式轉換為字符串

[英]Convert SQL Date time format to String

當閱讀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();
        }
    }

首先不要將原始值轉換為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");

分開“如何從合適的類型的數據庫中獲取數據的問題”這一問題很重要。 來自“我應該如何向用戶展示數據?”

嘗試類似:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM