如何在C#中获取当前系统日期和时间并将其插入SQL Server数据库?

时间:2014-02-16 16:07:30

标签: c# sql sql-server

我想将系统的当前日期和时间从C#应用程序插入到SQL Server数据库中。

C#以什么格式获取SQL Server接受的系统日期?

4 个答案:

答案 0 :(得分:4)

你可以通过数据库本身来完成它,如下面的

INSERT INTO MyTable (MyDate) Values (GetDate())

或者,如果需要设置DateTime列值,可以使用参数

INSERT INTO MyTable (MyDate) Values (@MyDate)

cmd.Parameters.AddWithValue("@MyDate", DateTime.Now);

示例代码:

using (SqlConnection con = new SqlConnection(clsConnection.getConnectionString()))
using (SqlCommand command = new SqlCommand("insert into HMS.dbo.CheckInOut(Room_No,Name,DateTime,CheckInOut) Values(02,'Name',GETDATE(),'CheckIn')", con))
{
    con.Open();
    command.ExecuteNonQuery();
    lblmissing.Text = "Recorded Inserted Successfully"; 
}

答案 1 :(得分:1)

您可以使用

DateTime.Now; /* to get the date time */

然后使用

将其插入SQL数据库
"INSERT INTO table_name (Date) VALUES (@0)", DateTime.Now

请注意,格式必须匹配。您不能只创建日期时间并插入它。

以下是我的数据库中的格式: 2/7/2014 11:14:14 PM 。虽然它不是DateTime.Now但它会告诉你格式是什么,它是在几天前(7日)被捕获的。

答案 2 :(得分:0)

对于C#:

DateTime dateTimeNow = DateTime.Now;

要插入sql-server:

SqlParameter param = new SqlParameter(parameterName, SqlDbType.DateTime);
param.Direction = ParameterDirection.Input;
param.Value = dateTimeNow;     

答案 3 :(得分:-4)

如果您只想获得分钟和秒钟,请使用

DateTime.Now.ToShortDateString();