3

I use GETDATE() in a SQL Server stored procedure to insert a date into the SQL Server database table.

After that I need to implement a C# function which is based on datetime input parameter finds if the date was saved in the tables.

The datetime in C# and SQL are different. How do I convert from C# datetime to SQL datetime which has a form of yyyy-mm-ddT:yy:mm:ss.mmm? I need to specify explicitly yyyy-mm-ddT:yy:mm:ss.mmm.

Will be happy for all propositions/possible ways.

2
  • 1
    I'm not sure what the format has to do with the comparison at all? Commented Jan 14, 2014 at 14:41
  • 1
    No, DATETIME in T-SQL and DateTime in .NET are not different - you can represent any DATETIME in SQL Server as a .NET DateTime. DATETIME in SQL Server has limits in terms of range (1-Jan-1753 to 31-Dec-9999) and accuracy (3.33ms) but it's deprecated in SQL Server 2008 anyway and shouldn't be used anymore; use DATE (if you only need date - no time) or DATETIME2(n) instead Commented Jan 14, 2014 at 15:24

5 Answers 5

5

DateTime in .Net framework and SQL Server (if it is DateTime type field) is irrespective of the format. Format is only useful for displaying output.

If your field in SQL Server is of DateTime type then you can query it from C# code using parameterized query something like:

public DataTable GetRecords(DateTime dtParameter)
{
    DataTable dt = null;
    using (SqlConnection conn = new SqlConnection("connection string"))
    {
        using (SqlCommand cmd = new SqlCommand("SELECT * from yourTable where DateField = @dateparameter"))
        {
            conn.Open();
            cmd.Parameters.AddWithValue("@dateparameter",dtParameter);
            SqlDataReader dr = cmd.ExecuteReader();
            //...rest of the code
            dt.Load(dr);
        }
    }
    return dt;
}
Sign up to request clarification or add additional context in comments.

14 Comments

the datetime should be argument provided by user
@Yakov, thats fine you, you can replace DateTime.Now with the parameter passed by user. It should be of type DateTime in .Net framework.
@Yakov, format doesn't matter. What is the type of field in SQL table ?
@Yakov :: If you are taking the value from user, you can simply parse it into a datetime object. here is a nice article. dotnetperls.com/datetime-parse
Are you asking your user to provide seconds and millisecond?
|
4

Datetimes between C# and SQL are 100% compatible. The format shouldn't make any difference if you are passing them as DateTimes. If you are generating a SQL string then I would highly recommend changing to SQL Parameters so you don;t have to worry about any formatting issues.

Comments

2

A datetime has no format at all, it has a value. SQL-DateTimes and C# DateTimes are compatible. So don't convert it (to string) at all but pass it as datetime-parameter to the database.

Then you're safe if the DateTime value is within SqlDateTime.MinValue(January 1, 1753) and SqlDateTime.MaxValue(December 31, 9999).

1 Comment

Ive passed the value.But the sql store procedure doesnt find this value in the tables.Besides that it is in.Probably the seconds part is missing
2

You should never write DateTime.Now from client code to insert into the database as this will be based on the clients local time; do this

public DateTime GetDatabaseTime()
{
    var parameter = new SqlParameter("time", SqlDbType.DateTime2)
    {
        Direction = ParameterDirection.Output
    };

    using (var connection = new SqlConnection(ConnectionString))
    {
        connection.Open();

        using (var command = new SqlConnection("SELECT @time = SYSDATETIME()", connection))
        {
            command.ExecuteNonQuery();
        }
    }

    return (DateTime)parameter.Value;
}

Also you should never use DATETIME in SQL Server you should always use DATETIME2 as DATETIME is less accurate than C#::DateTime and it will lead to rounding errors. I know this from bitter experience.

Comments

2

If you are using Entity Framework, and your database is using datetime and not datetime2, the trick is to use SqlDateTime to match the fact that .Net goes to nanosecond, versus sql's millisecond precision. You can use your DateTime variable in .net.. for a SqlDateTime instance, and then you can uniquely identify a record down to the millisecond.

System.Data.SqlTypes.SqlDateTime entry2 = new System.Data.SqlTypes.SqlDateTime(new DateTime(dto.LookUpDateTime));
DateTime entry = entry2.Value;

var existticket = from db in context.Tickets
                              where db.LookupDateTime == entry && db.UserId == UserId
                              select db;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.