简体   繁体   English

在C#SQL中无法将字符串识别为有效的DateTime

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

I am a beginner in C#. 我是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. 无法将字符串识别为有效的DateTime。

Here is my sqlCommand Syntax: 这是我的sqlCommand语法:

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"); 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. 我也遇到了将字符串解析为Date的问题。 But nothing helped. 但是没有任何帮助。 The issue was in Microsoft date and time settings. 问题出在Microsoft日期和时间设置中。 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. 希望它会帮助某人。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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