标签: format

  • 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>
      <ASP:BoundColumn DataField="CheckoutTime" DataFormatString="{0:yyyy-MM-dd HH24:mm:ss}">
      </asp:BoundColumn>

    • 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.
      Convert.ToDateTime("2008-12-09").ToString;
      Convert.ToDateTime(dr["PubDate"]).ToShortDateString();

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

    • Show only year and month.
      DataBinder.Eval(Container.DataItem,"starttime","{0:yyyy-MM}");

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

    Technorati Tags: ,,