如何使用EntityFramework将日期格式化为SQL服务器 [英] How to format a Date into SQL server using EntityFramework

查看:350
本文介绍了如何使用EntityFramework将日期格式化为SQL服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试存储到我的数据库中,只有日期不是日期和时间,只有日期,但它总是与时间在一起。

I'm trying to storage into my database ONLY the DATE not DATE AND TIME, only Date, but it always came with the time together.

这是怎么回事我只能存储String中的日期:

This is how I do to storage only the date inside of String :

string.Format("{0:dd/MM/yyyy}", DateTime.Now)

可以正常工作,但现在,我想将StringDate存储到日期在我的SQL Server数据库。所以我这样做:

And works fine, but now, I want to storage a StringDate to a Date in my SQL Server database. So I did this :

EntityTable ...

EntityTable...

 [Column(TypeName = "date")]
 public DateTime? InicialDate { get; set; }

控制器

InicialDate = DateTime.ParseExact("01-12-2016",
                             "dd/MM/yyyy",
                             new CultureInfo("pt-BR"));

在我的桌子里面,日期不是按照我预期的正确格式,我来了这个:

And inside of my Table, the Date is not at the right format as I expected, I came like this :

2017-12-01 and not, DAY-MONTH-YEAR....

如果我尝试查询并检索日期,我就像这样:

And if I try to make a query and retrieve the date, i came like this :

"InicialDate": "2017-12-01T00:00:00"

我只想在没有时间的情况下保存DATE!

I just want to save ONLY the DATE without time!

推荐答案

DateTime内部只是一个number(可能是一个int / long,表示自Epoch以来的秒数;不知道这个),但是在这里并不重要)以及它作为字符串显示的方式取决于使用的格式。 DateTime.ParseExact(01-12-2016,dd / MM / yyyy,新的CultureInfo(pt-BR)); 将日期解析为DateTime内根据用于显示日期的pt-BR规则表示,然后当EF发布到db时,将内部表示转换为ISO-8601文本形式(因为SQL是基于文本的),则db引擎将其转换为数字形式存储。当您查看数据库时,您会看到它为 2017-12-01 ,因为您用于执行此操作的工具设置为以ISO-8601格式显示日期。

DateTime is internally just a single number (probably an int/long, representing the number of seconds since the Epoch; not sure about this, though; but it doesn't really matter here) and how it's displayed as a string depends on the format used. DateTime.ParseExact("01-12-2016", "dd/MM/yyyy", new CultureInfo("pt-BR")); parses the date into DateTime internal representation according to the pt-BR rules for displaying date, then when EF is posting this to the db it converts the internal representation to ISO-8601 textual form (because SQL is text-based), then the db engine again converts it into a number form and stores it. When you look in the db, you see it as 2017-12-01, because the tool you use to do this is set up to display dates in the ISO-8601 format.

所以,日期存储正确,您的种子取决于特定应用程序用于显示日期的格式。

So, the date is stored correctly, what you seed depends on the format the particular app uses to display dates.

这篇关于如何使用EntityFramework将日期格式化为SQL服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆