简体   繁体   中英

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.

this is what i need to do

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM