I am trying to update a datetime
column in a SQL Server 2012 table by using
newItem.DateSaved = DateTime.Today;
I want to save only the Date
part of DateTime
, but when I am checking in the table I can see that it saves also the time part: 2018-07-27 00:00:00.000
. How I can make it to store only date
part? 2018-07-27
?
Edit
Because my column is datetime
, I see that I can't store only the date part. But how I can show to the user only the date part without time? Here is the select part of the Linq-to-SQL query:
select new { Date = smv.DateSaved.Value.Date }).Distinct();
A datetime
column always has a time part - just, in your case it will all be zeros. A datatime
is just a number under the hood; it doesn't have any choice about what it has / doesn't have; similarly, it doesn't have any notion of formatting until your code tries to display it, and then it is the dispalying code that chooses the format.
If you don't want a time part, use date
instead of datetime
for your column.
在SQL Server中将列类型从datetime
更改为date
( https://docs.microsoft.com/en-us/sql/t-sql/data-types/date-transact-sql?view=sql-server-2017 )
If you want to store only the date without time in SQL Server database you can set the column type to date
ALTER TABLE table_name
ALTER COLUMN DateSaved date;
Reference: https://docs.microsoft.com/en-us/sql/t-sql/data-types/date-transact-sql?view=sql-server-2017
If you have a DateTime
property in your model and you want to show only the date part just format it in your control in the View. For example:
$"{newItem.DateSaved:yyyy-MM-dd}"
or
newItem.DateSaved.ToString("yyyy-MM-dd")
You can also use "d"
or "D"
(short and long version) instead of specific format like "yyyy-MM-dd"
if you want to have default formatting.
If your view is written in HTML or XAML do it there using the same formatting technique.
It is because your field on the database is DateTime
. If you want to store just date, you should have a field with date data type. In this link , you can see the difference between the date data types.
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.