TransWikia.com

conversion failed when converting datetime from character string while inserting and updating to database

Database Administrators Asked by Mark Luzon on February 15, 2021

I’m trying to insert time and date separately and calculate if it is late to the set time and then insert it to database…

here’s my try code for update

string Date = DateTime.Now.ToString("dd-MM-yyyy");
string Time = DateTime.Now.ToString("h:mm:ss tt");
SqlCommand comm2 = conn.CreateCommand();
comm2.CommandText = "Update Time_Logs SET Time_Out = ‘" + Time + "’ where Emp_Id = ‘" + EmpId.Text + "’ and Date = ‘" + Date + "’";
try
{
conn.Open();
comm2.ExecuteNonQuery();
MessageBox.Show("Time_Out…");
conn.Close();
TimeCompute();
}
catch (Exception x)
{
MessageBox.Show(x.Message);
conn.Close();
}

and here is the code for inserting

string Date = DateTime.Now.ToString("dd-MM-yyyy");
string Time = DateTime.Now.ToString("h:mm:ss tt");

        SqlCommand comm = conn.CreateCommand();
        comm.CommandText = "INSERT INTO Time_Logs (Emp_Id, Date, Time_In) VALUES('" + EmpId.Text + "','" + Date + "','" + Time + "')";
        try
        {
            conn.Open();
            comm.ExecuteNonQuery();
            MessageBox.Show("Time_In...");
            conn.Close();
            DateTime time = DateTime.Parse(Time);
            DateTime inDate = DateTime.Parse("8:00:00 AM");
            TimeSpan ts1 = inDate.TimeOfDay;
            TimeSpan ts = time - inDate;
            if (ts < ts1)
            {
                SqlCommand comm2 = conn.CreateCommand();
                comm2.CommandText = "Update Time_Logs SET Late = '" + ts + "' where Emp_Id = '" + EmpId.Text + "' and Date = '" + Date + "'";
                conn.Open();
                comm2.ExecuteNonQuery();
                conn.Close();
            }
            else
            {
                SqlCommand comm2 = conn.CreateCommand();
                comm2.CommandText = "Update Time_Logs SET Late = '" + ts + "' where Emp_Id = '" + EmpId.Text + "' and Date = '00:00:00'";
                conn.Open();
                comm2.ExecuteNonQuery();
                conn.Close();
            }
        }
        catch (Exception x)
        {
            MessageBox.Show(x.Message);
            conn.Close();
        }

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP