Romain
Romain

Reputation: 859

SQL Server DateTime Object and C# Datetime using Entity Framework

I am pretty new to Entity Framework, I was able to create a process to add new entry to a database. However the last attribute in SQL Server is a datetime type. When I fill it using from the C# application it only includes the year month and day but not the time (cf the second entry below)

newEntry.TimeStamp = DateTime.Today;

(new entry is an instance of one of the class created by Entity Framework).

enter image description here

My initial idea was to change the format using :

string sqlFormatedDate = DateTime.Today.ToString("yyyy-MM-dd HH:mm:ss");

But obviously the application does not accept the type string when I get to the line :

newEntry.TimeStamp = sqlFormatedDate;

I get the error

Cannot Implicitly convert type 'string' to 'System.DateTime?'

How can one create a datetime object in C# that will properly be displayed in SQL Server?

EDIT:

Turns out one just has to use Datetime.now

Upvotes: 0

Views: 2920

Answers (2)

Giorgi Nakeuri
Giorgi Nakeuri

Reputation: 35790

https://msdn.microsoft.com/en-us/library/system.datetime.today(v=vs.110).aspx

Property Value
Type: System.DateTime
An object that is set to today's date, with the time component set to 00:00:00.

Use DateTime.Now instead which will return date with time part.

Upvotes: 1

christophano
christophano

Reputation: 935

DateTime.Today is only the Date portion of the DateTime, the time is set to midnight. I think what you need is DateTime.Now.

Upvotes: 2

Related Questions