简体   繁体   中英

Issue with DateTime format C#

I need help with my code. I want to insert a DataTable in to Sql Table. I wrote a code for that but I'm getting an format error which I cannot solve? On my SQl Table I have format set yyyy-MM-dd hh:mm:ss:000 but in the datatable I have format: 04/15/2020 06:01:33 AM

I'm getting an error:

Commit Exception Type: System.FormatException Message: String '04/15/2020 06:01:33 AM' was not recognized as a valid DateTime.

using System;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
    DataTable dt = new DataTable();


        dt.Columns.Add("BP_Queue");
        dt.Columns.Add("BP_Key");
        dt.Columns.Add("BP_Status");
        dt.Columns.Add("BP_Loaded");
        dt.Columns.Add("BP_Deferred");
        dt.Columns.Add("BP_Completed");
        dt.Columns.Add("BP_Excepted");
        dt.Columns.Add("BP_Exception_Type");
        dt.Columns.Add("BP_Exception_Reason");


        DataRow r = dt.NewRow();
        r[0] = "test";
        r[1] = "123";
        r[2] = "Completed";
        r[3] = "4/15/2020 06:01:33 AM";
        r[4] = null;
        r[5] = "4/15/2020 06:01:33 AM";
        r[6] = null;
        r[7] = null;
        r[8] = null;

        dt.Rows.Add(r);

        string connectionstring = null;
        string username = @"test";
        string password = @"1234";
        string servername = @"server";
        string database = "test";
        string sqlQuery = "INSERT INTO RPA_QUEUES_BASIC_DATA (BP_Queue,BP_Key,BP_Status,BP_Loaded,BP_Deferred,BP_Completed,BP_Excepted,BP_Exception_Type,BP_Exception_Reason) VALUES (@BP_Queue,@BP_Key,@BP_Status,@BP_Loaded,@BP_Deferred,@BP_Completed,@BP_Excepted,@BP_Exception_Type,@BP_Exception_Reason);";
        SqlConnection conn;
        SqlTransaction transaction;
        connectionstring = "Server="+servername+";Database="+ database + ";User Id="+username+";Password="+password+";";

        using (conn = new SqlConnection(connectionstring))
        {
            conn.Open();
            transaction = conn.BeginTransaction("Transaction");
            string customerInsert = sqlQuery;

            using (SqlCommand query = new SqlCommand(customerInsert))
            {

                query.Connection = conn;
                query.Transaction = transaction;
                query.Parameters.Add("@BP_Queue", SqlDbType.NVarChar, 255);
                query.Parameters.Add("@BP_Key", SqlDbType.NVarChar, 255);
                query.Parameters.Add("@BP_Status", SqlDbType.NVarChar, 50);
                query.Parameters.Add("@BP_Loaded", SqlDbType.DateTime);
                query.Parameters.Add("@BP_Deferred", SqlDbType.DateTime);
                query.Parameters.Add("@BP_Completed", SqlDbType.DateTime);
                query.Parameters.Add("@BP_Excepted", SqlDbType.DateTime);
                query.Parameters.Add("@BP_Exception_Type", SqlDbType.NVarChar, 255);
                query.Parameters.Add("@BP_Exception_Reason", SqlDbType.NVarChar,-1);
                try
                {
                    using (SqlTransaction tr = transaction)
                    {
                        foreach (DataRow row in dt.Rows)
                        {
                            //query.Parameters.Clear();
                            query.Parameters["@BP_Queue"].Value = row["BP_Queue"];
                            query.Parameters["@BP_Key"].Value = row["BP_Key"];
                            query.Parameters["@BP_Status"].Value = row["BP_Status"];
                            query.Parameters["@BP_Loaded"].Value = row["BP_Loaded"].ToString() == "" ? DateTime.ParseExact("1/01/1900 00:00:00 AM", "M/dd/yyyy H:mm:ss tt", CultureInfo.InvariantCulture) : DateTime.ParseExact(row["BP_Loaded"].ToString(), "M/dd/yyyy H:mm:ss tt", CultureInfo.InvariantCulture);
                            query.Parameters["@BP_Deferred"].Value = row["BP_Deferred"].ToString() == "" ? DateTime.ParseExact("1/01/1900 00:00:00 AM", "M/dd/yyyy H:mm:ss tt", CultureInfo.InvariantCulture) : DateTime.ParseExact(row["BP_Deferred"].ToString(), "M/dd/yyyy H:mm:ss tt", CultureInfo.InvariantCulture);
                            query.Parameters["@BP_Completed"].Value = row["BP_Completed"].ToString() == "" ? DateTime.ParseExact("1/01/1900 00:00:00 AM", "M/dd/yyyy H:mm:ss tt", CultureInfo.InvariantCulture) : DateTime.ParseExact(row["BP_Completed"].ToString(), "M/dd/yyyy H:mm:ss tt", CultureInfo.InvariantCulture);
                            query.Parameters["@BP_Excepted"].Value = row["BP_Excepted"].ToString() == "" ? DateTime.ParseExact("1/01/1900 00:00:00 AM", "M/dd/yyyy H:mm:ss tt", CultureInfo.InvariantCulture) : DateTime.ParseExact(row["BP_Excepted"].ToString(), "M/dd/yyyy H:mm:ss tt", CultureInfo.InvariantCulture);
                            query.Parameters["@BP_Exception_Type"].Value = row["BP_Exception_Type"];
                            query.Parameters["@BP_Exception_Reason"].Value = row["BP_Exception_Reason"];
                            query.ExecuteNonQuery();
                        };
                        tr.Commit();
                    }
                    conn.Close();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Commit Exception Type: {0}", ex.GetType());
                    Console.WriteLine("   Message: {0}", ex.Message);

                    try
                    {
                        transaction.Rollback();
                    }
                    catch (Exception ex2)
                    {
                        Console.WriteLine("Rollback Exception Type: {0}", ex2.GetType());
                        Console.WriteLine("   Message: {0}", ex2.Message);
                    }
                };
            };
        };

Thank you for any help!

using System.Globalization;

Then the code:

DateTimeFormatInfo df1 = new DateTimeFormatInfo();
df1.DateSeparator = "/";
df1.TimeSeparator = ":";
df1.PMDesignator = "pm";
df1.AMDesignator = "am";

DateTime d = DateTime.MinValue;

DateTime.TryParseExact("4/15/2020 06:01:33 AM", "M/d/yyyy hh:mm:ss tt", df1, DateTimeStyles.AllowWhiteSpaces, out d);

string sqlDate = d.ToString("yyyy-MM-dd HH:mm:ss");

I believe you can set the date value directly to SQL database like this:

DateTime dateLoaded = DateTime.MinValue;
DateTime.TryParseExact(row["BP_Loaded"].ToString(), "M/d/yyyy hh:mm:ss tt", df1, DateTimeStyles.AllowWhiteSpaces, out dateLoaded);
query.Parameters["@BP_Loaded"].Value = dateLoaded;

The issue was that the cells of the colums had null values. I could solve the issue in which I have written a method to convert the data in to DataTime format like this:

query.Parameters["@BP_Loaded"].Value = ExtractDate(row["BP_Loaded"].ToString());
query.Parameters["@BP_Deferred"].Value = ExtractDate(row["BP_Deferred"].ToString());
query.Parameters["@BP_Completed"].Value = ExtractDate(row["BP_Completed"].ToString());
query.Parameters["@BP_Excepted"].Value = ExtractDate(row["BP_Excepted"].ToString());

Method:

    public static SqlDateTime ExtractDate(string myDate)
            {
                //Set default value if error
                SqlDateTime result = SqlDateTime.MinValue;
                if (myDate != "")
                {
                    try
                    {
                        result = SqlDateTime.Parse(myDate);
                    }
                    catch (Exception)
                    {
                        return (result);
                    }
                }
                return (result);
            }

Hope this can help other.

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