SQLDataReader GetDateTime格式

时间:2014-07-07 03:38:06

标签: c# asp.net sql

检查下面的代码:

HTML页面:

<table width="100%" align="right" cellpadding="2" cellspacing="2" border="0" bgcolor="#EAEAEA">
    <tr align="center" style="background-color: yellow; color: black;">
        <th colspan="2">Fauzan</th>
        <th colspan="2">Febri</th>
    </tr>
    <tr align="left" style="background-color: gray; color: black;">
        <td>ID</td>
        <td>Number01</td>
        <td>TheDate</td>
        <td>Number02</td>
    </tr>
    <%=getWhileLoopData()%>
</table>

代码背后:

public string getWhileLoopData() 
{
 string htmlStr = "";
 SqlConnection thisConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);
 SqlCommand thisCommand = thisConnection.CreateCommand();
 thisCommand.CommandText = "SELECT * FROM MyTable WHERE TheDate = @TheDate";
 thisCommand.Parameters.AddWithValue("@TheDate", txtDate.Text);

 thisConnection.Open();
 SqlDataReader reader = thisCommand.ExecuteReader();

 while (reader.Read()) {
     int id = reader.GetInt32(0);

     int Number01 = reader.GetInt32(1);
     DateTime TheDate = reader.GetDateTime(2);
     Decimal Number02 = reader.GetDecimal(3);

     //string Pass = reader.GetString(2);
     htmlStr += "<tr><td>" + id + "</td><td>" + Number01 + "</td><td>" + TheDate + "</td><td>" + Number02 + "</td></tr>";
 }

 thisConnection.Close();
 return htmlStr;
}

问题是,我如何格式化数据阅读器?喜欢,&#34; TheDate&#34;领域,从&#39; 6/18/2014 12:00:00 AM&#39;至&#39; 18 / Jun / 2014&#39;。也适用于&#39; Number02&#39;字段,我该如何格式化呢?喜欢,来自&#39; 0.829&#39;成为&#39; 0.83&#39;。

1 个答案:

答案 0 :(得分:2)

您可以使用ToString()和Custom Date and Time Format Strings

格式化日期时间
string strDate = TheDate.ToString("dd/MMM/yyyy");

您可以使用Math.Round格式化数字

Number02 = Math.Round(Number02, 2);

您可以直接格式化您正在制作的html字符串中的日期和数字

htmlStr += "<tr><td>" + id + "</td><td>" + Number01 + "</td><td>" +
   TheDate.ToString("dd/MMM/yyyy") + "</td><td>" +  Math.Round(Number02, 2) + "</td></tr>";