Nyprez Nyprez - 5 months ago 30
SQL Question

Get current date and time, using c# for ms access

I can only find out how to get current date, not the combination of current date and time. I haven't found any fitting solution.

cmd.CommandText = "INSERT INTO [Table] (DATE) VALUES (@date)";

var pDate = new OleDbParameter("@date", SqlDbType.DateTimeOffset);
pDate.Value = DateTime.Now.Date;
cmd.Parameters.Add(pDate);


Any help would be much appreciated.

EDIT: Also tried:

var dateAndTime = DateTime.Now;
var date = dateAndTime.Date;


But I'm still just receiving the date"6/12/2016", not the time.

Answer

Access SQL supports a function named Now() which returns the current date and time.

So it would be simpler to let the db engine use Now() instead of deriving the equivalent value in c# and then feeding that value to your INSERT as a parameter.

cmd.CommandText = "INSERT INTO [Table] ([DATE]) VALUES (Now())";

Note Date is a Jet reserved word. Enclose that name in square brackets in the INSERT to signal the db engine you mean an object name instead of the Date() function.