You must Sign In to post a response.

How to add date time in sql databae using c#

hi

How to add date time in sql databae using c#


Comments

Author: Paritosh Mohapatra17 Sep 2012 Member Level: Gold   Points : 3

SQL Server supports some specific date formats. You may use yyyy-MM-dd format.

Please check the following code:


string dt = DateTime.Now.ToString("yyyy-MM-dd");


You should not worry about how the date is stored. You can display the date in any format you want and it can be done in SQL Server as well as .Net.

Author: Asheej T K17 Sep 2012 Member Level: Gold   Points : 4

Hi,

I guess you wanted to insert date in the database using c#. Please check below code.


protected void btnSave_Click(object sender, EventArgs e)
{
//Get the connection string details frm web.config
con = new SqlConnection(constr);
con.Open();
cmd = new SqlCommand("insert into Employee (FName,LName,Address,DOB)values (@FName,@LName,@Address,@DOB)", con);

cmd.Parameters.Add(new SqlParameter("@FName", txtFName.Text));
cmd.Parameters.Add(new SqlParameter("@LName", txtLName.Text));
cmd.Parameters.Add(new SqlParameter("@Address", txtAddress.Text));
cmd.Parameters.Add(new SqlParameter("@DOB", txtDOB.Text));

cmd.ExecuteNonQuery();

}

Author: SQL Programmers17 Sep 2012 Member Level: Gold   Points : 2

Hi,

You can check the following code

SqlCommand cmd = new SqlCommand("INSERT INTO () VALUES (@values)", connection);
cmd.Parameters.AddWithValue("@value", dateTimeVariable);

cmd.ExecuteNonQuery();

Author: Pawan Awasthi17 Sep 2012 Member Level: Gold   Points : 2

Hai Pavan Kumar,
To add the date with time in sql server, you need to send from C# as the date with its format like mm/dd/yyyy hh:mm:ss and then it will be saved as the date with the current time.
Hope it will be helpful to you.

Author: Ravindran17 Sep 2012 Member Level: Diamond   Points : 4

Hi,

Create table like this


create table empdt(dte datetime)


And insert like this format yyyy-MM-dd

using System.Data;
using System.Data.SqlClient;
public partial class InsertNewRecord : System.Web.UI.Page
{
SqlConnection sqlcon=new SqlConnection(@"Server=RAVI-PC\SQLEXPRESS;database=test;uid=xxxx;pwd=yyyy;"); //chaneg server details
SqlCommand sqlcmd=new SqlCommand();
protected void Button1_Click(object sender, EventArgs e)
{
SqlCommand sqlcmd = new SqlCommand("insert into empdt(dte) values('" + Convert.ToDateTime(TextBox1.Text).ToString("yyyy-MM-dd") + '), sqlcon);
sqlcmd.CommandType = CommandType.Text;
sqlcon.Open();
sqlcmd.ExecuteNonQuery();
sqlcon.Close();
}
}

Author: John Bhatt18 Sep 2012 Member Level: Gold   Points : 2


string Date = DateTime.Now.ToString();

You can save this in Database in the Column Type of Date, DateTime, varchar, nvarchar and Text.


Sign In to post your comments