[英]How can I store only the date portion of the datetime. Today property to a SQL Server table datetime column?
I am trying to update a datetime
column in a SQL Server 2012 table by using 我试图通过使用更新SQL Server 2012表中的datetime
列
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
. 我想只保存DateTime
的Date
部分,但是当我在表中检查时,我可以看到它还节省了时间部分: 2018-07-27 00:00:00.000
。 How I can make it to store only date
part? 我怎么能只存储date
部分? 2018-07-27
? 2018-07-27
?
Edit 编辑
Because my column is datetime
, I see that I can't store only the date part. 因为我的列是datetime
,所以我看到我不能仅存储日期部分。 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: 以下是Linq-to-SQL查询的选择部分:
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. datetime
时间列始终具有时间部分 - 在您的情况下,它将全部为零。 A datatime
is just a number under the hood; 甲datatime
只是引擎盖下的数; 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. 同样,它没有格式的任何想法,直到你的代码试图显示它,然后它是选择的格式dispalying代码。
If you don't want a time part, use date
instead of datetime
for your column. 如果您不想要时间部分,请使用date
而不是datetime
时间作为列。
在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
如果要在SQL Server数据库中仅存储没有时间的日期,可以将列类型设置为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 参考: 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. 如果模型中有DateTime
属性,并且只想显示日期部分,则只需在视图中的控件中对其进行格式化。 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. 如果您想要默认格式,也可以使用"d"
或"D"
(短版和长版)而不是像"yyyy-MM-dd"
这样的特定格式。
If your view is written in HTML or XAML do it there using the same formatting technique. 如果您的视图是用HTML或XAML编写的,请使用相同的格式化技术。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.