简体   繁体   English

ASP.NET和SQL Server日期时间问题

[英]asp.NET and SQL Server datetime issues

I am having hard time to store date information into the datetime column of SQL Server. 我很难将日期信息存储到SQL Server的datetime列中。

I get the input from the user for three columns: 我从用户那里得到了三列的输入:

  1. Creation Date 创建日期
  2. Preparation Date 准备日期
  3. Next Preparation Date 下次准备日期

I use calendarextender and format the date as "yyyy/MM/dd". 我使用calendarextender并将日期格式设置为“ yyyy / MM / dd”。 When all the fields have date, they are stored in the DB as for instance, 16-10-2016 (dd-MM-yyyy). 当所有字段都有日期时,它们将存储在数据库中,例如16-10-2016(dd-MM-yyyy)。

At this point I have two issues: 此时,我有两个问题:

  1. These columns are optional, when some of them are empty my code does not work (I assume because datetime cannot be null). 这些列是可选的,当其中一些为空时,我的代码不起作用(我假设是因为datetime不能为null)。 To overcome this, I am using the following code snippet but still does not work. 为了克服这个问题,我使用了以下代码片段,但仍然无法正常工作。

     DateTime? creationDate= null; if (creationDateTextbox.Text != null && creationDateTextbox.Text != "") { creationDate= Convert.ToDateTime(creationDateTextbox.Text); } 
  2. When I fetch the dates from DB, they are shown as 10/16/2016 (MM-dd-yyyy) which is different how I formatted it. 当我从数据库中获取日期时,它们显示为2016年10月16日(MM-dd-yyyy),与我格式化日期的方式不同。 I would like to show it in the format user enters them. 我想以用户输入的格式显示它。

Dates do not have a format while stored in a database. 日期存储在数据库中时没有格式。 It is actually usually just a very large long that counts the number of milliseconds from a set starting date. 实际上,它通常只是一个很大的long ,它从设定的开始日期开始算起毫秒数。

If you want to store the format you need to stop storing it as dates and instead just treat the text as text in the database, however if you do this you won't get the advantage of sorting or filtering by a date range because it will just be seen as text. 如果要存储格式,则需要停止将其存储为日期,而只是将文本视为数据库中的文本,但是,如果这样做,则将无法获得按日期范围排序或过滤的优势,因为它将只是被视为文字。

日期时间没有任何格式您可以格式化为字符串,假设您的DateTime类型数据库字段dt包含日期为10/16/2016 (MM-dd-yyyy)则可以将其转换

string s = dt.ToString("yyyy/MM/dd");

The answer to one of your questions is here: MSDN You can use data annotations to format the dates that you get from your SQL DB. 您的问题之一的答案在这里: MSDN您可以使用数据批注来格式化从SQL DB获得的日期。 I'm assuming that you're using EF6; 我假设您使用的是EF6; if not, you can change the field to a varchar in SSMS, and store the date as a String. 如果不是,则可以在SSMS中将该字段更改为varchar,然后将日期存储为字符串。

And the second, I'm unclear about, but if what you want is for your SQL DB column to be optional, you can use the Optional data annotation for that. 第二点,我不清楚,但是如果您希望SQL DB列是可选的,则可以使用Optional数据注释。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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