You must Sign In to post a response.
  • Category: .NET

    How to add date time in sql databae using c#


    How to add date time in sql databae using c#
  • #688750
    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.

    Thanks & Regards
    Paritosh Mohapatra
    Microsoft MVP (ASP.Net/IIS)
    DotNetSpider MVM

  • #688753

    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);
    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));



    Asheej T K

  • #688757

    You can check the following code

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


    SQL Server Programmers and Consultants

  • #688765
    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.

    Pawan Awasthi(DNS MVM)
    +91 8123489140 (whatsApp), +60 14365 1476(Malaysia)

  • #688820

    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;

    Your Hard work never fails

  • #689002

    string Date = DateTime.Now.ToString();

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

    Glad to be,
    John Bhatt
    Editor - DNS Forums

  • This thread is locked for new responses. Please post your comments and questions as a separate thread.
    If required, refer to the URL of this page in your new post.