简体   繁体   中英

asp.NET and SQL Server datetime issues

I am having hard time to store date information into the datetime column of SQL Server.

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". When all the fields have date, they are stored in the DB as for instance, 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). 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. 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.

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. I'm assuming that you're using EF6; if not, you can change the field to a varchar in SSMS, and store the date as a String.

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.

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