Displaying DateTime Object as Desired

DateTime is a common type we deal with frequently in the development of C#-ASP.NET project. As a result, how to display a DateTime object properly is the knowledge we have to know as a web service developer.

In the following paragraphs, I made a summary of formatting DateTime object in several circumstances to get it displayed as needed:

  • Format DateTime string retrieved from database and to be binded to Data Controls.
    <ASP:BoundColumn DataField="JoinTime" DataFormatString="{0:yyyy-MM-dd}" >
    <ASP:BoundColumn DataField="CheckoutTime" DataFormatString="{0:yyyy-MM-dd HH24:mm:ss}">

  • Statement in the CodeFile to get a DateTime string.
    e.Item.Cell[0].Text = Convert.ToDateTime(e.Item.Cell[0].Text).ToShortDateString();

  • With the help of String class.
    String.Format( "yyyy-MM-dd ", theDateTimeObj);

  • With the help of Convert method.

  • ToString method of DateTime class.
    DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss");

  • Show only year and month.

Certainly, there are more situations when you have to format a DateTime object, and the rules could be deduced from above.

Technorati Tags: ,,



您的电子邮箱地址不会被公开。 必填项已用 * 标注