I have a column in my datatable which is of DateTime Type. I only want the DatePart, hence when I use the ToShortDateTimeString it converts to short date but of string type. Hence when i reassign the string to the column of the datatable it again appends 12:00:00 to it. I cannot change the column type in my datatable. Is there any way to convert DateTime to ShortDateTime directly witho开发者_开发知识库ut converting to string?????
No, that is not possible. Formatting it into a string doesn't help either.
The datetime
type in the database always has both a date and time component. If you don't specify the time component it becomes 00:00:00
(or 12:00:00 AM
in 12 hour format). So, whatever you do to try to remove the time compontent, it will still have one.
Note that the datetime
value in the database doesn't have a format. It's just a value representing a point in time.
So, you have to take care of the data whenever you read if from the database. If you just use the default settings to format the date value into a string, you will get both the date and time components, as they are always there. You have to specify the format that you want when converting the DateTime value to a string for display. For example:
string formatted = theDateTimeValue.ToString("yyyy-MM-dd");
If Dealing with DataGrids or GridViews, in date column format it using {0:d}, or simple D. If you are on web and using itemplate with table, tr and td and using binding template like <%# Eval()%> then you try the following
<span><%#string.Format("{0:d}",Eval("DataTableFieldName"))%></span>
You can use the .Date
property, like this:
DateTime.Now.Date //just the date portion, like DateTime.Today would give
If you wanted to format on display, e.g. in a GridView, you can add the format to your column using the DataFormatString
property, like this:
<asp:BoundField DataField="ColumnName" DataFormatString="{0:yyyy-MM-dd}" HtmlEncode="false" />
精彩评论