简体   繁体   中英

c# add am/pm to my (string)date value automatically

I have a datagridview will display the date value which extracted from database (mysql), see the pic 在此处输入图片说明

the value in database is (datatype is datetime)

2018-02-28 00:00:00
2017-02-02 00:00:00

in program code i set the value using this

dataObj.special_from_date = (string)productData.Tables[0].Rows[i]["special_from_date"].ToString();
dataObj.special_to_date = (string)productData.Tables[0].Rows[i]["special_to_date"].ToString();

Except datagridview cell, in textfield it also display the value with am/pm 上午/下午 text, anyone know what is the reason?

-------------------------update------------------------------

DateTime sfd = DateTime.Now;
    if (productData.Tables[0].Rows[i]["special_from_date"].ToString() != "") {
    //DateTime sfd = DateTime.TryParseExact(productData.Tables[0].Rows[i]["special_from_date"].ToString();
    MessageBox.Show("tet");
    if (DateTime.TryParseExact(productData.Tables[0].Rows[i]["special_from_date"].ToString(), "dd-MM-yyyy", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out sfd))
       {
                            // use d
        MessageBox.Show(sfd.ToString());
       }
    }

    public DataSet selectConnect(MySqlCommand cmd)
    {

        try
        {

            adapter = new MySqlDataAdapter();
            ds = new DataSet();

            cmd.CommandTimeout = 60;
            cmd.ExecuteNonQuery();

            adapter.SelectCommand = cmd;
            adapter.Fill(ds);

            adapter.Dispose();
            cmd.Dispose();


        }
        catch (Exception ex)
        {
            // Show any error message.
            MessageBox.Show(ex.Message);
        }

        return ds;

    } //connect

        dao dao = dao.GetInstance;
        databaseConnection = dao.connect();
        sqlCmd = new MySqlCommand(sql, databaseConnection);
        DataSet ds = new DataSet();


        databaseConnection.Open();
        ds = dao.selectConnect(sqlCmd);
        List<productData> products = dao.getProducts(ds);
        productData product = products.First();

It is because localization applied on your result automatically. You can format your date time at the time of converting to string which helps you to avoid this.

dataObj.special_from_date = productData.Tables[0].Rows[i]["special_from_date"].ToString("MM/dd/yyyy hh:mm:ss");

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