简体   繁体   中英

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

在此处输入图片说明

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM