简体   繁体   中英

String was not recognized as a valid DateTime in c# SQL

I am a beginner in C#. I have a textbox and a button.

When i click the button it displays datetime in textbox.

protected void btnStartTime_Click(object sender, EventArgs e)
{
    txtSrvStartTime.Text = DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss tt");
}

Now problem is when i update my page i'm getting an error

String was not recognized as a valid DateTime.

Here is my sqlCommand Syntax:

SelectCmd.Parameters.Add("@servStartTime", SqlDbType.DateTime).Value = DateTime.ParseExact(LblSrvEndTime.Text, "MM/dd/yyyy hh:mm:ss tt", null);

尝试这个

DateTime.ParseExact(LblSrvEndTime.Text, "MM/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture)

Thanks for your valuable time. I got the solution:

txtSrvStartTime.Text = DateTime.Now.ToString("h:mm:ss tt");

    SqlConnection connsv = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
    connsv.Open();
    string SelectQuery = @"UPDATE [Table_Name] SET 
                            [Service Start Time]=@servStartTime
                            WHERE [ID]=@shipnum";

    SqlCommand SelectCmd = new SqlCommand(SelectQuery, connsv);
    SelectCmd.Parameters.Add("@servStartTime", SqlDbType.DateTime).Value = txtSrvStartTime.Text;
    SelectCmd.ExecuteNonQuery();
    connsv.Close();

I also had the problem with a parsing of string to Date. But nothing helped. The issue was in Microsoft date and time settings. Try to play with it, because on the different machines, depends of this setting, we had or didn`t have such parsing problems with the same culture! Hope it will help someone.

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