我在数据库中将DateTime作为字符串,例如:6 @ 11 @ 2012 @ 1 @ 37 我有这样的解码方法:
public static DateTime DecodeTime(string time)
{
int day = Int32.Parse(time.Split('@')[0].Trim());
int month = Int32.Parse(time.Split('@')[1].Trim());
int year = Int32.Parse(time.Split('@')[2].Trim());
int hour = Int32.Parse(time.Split('@')[3].Trim());
int minute = Int32.Parse(time.Split('@')[4].Trim());
DateTime decode = new DateTime(year, month, day, hour, minute, 0);
return decode;
}
我要做的是尝试将信息放入数据集中,如下所示:
public DataSet GetAllBooking()
{
string connString = ConfigurationManager.ConnectionStrings["SQL2012_892524_amritConnectionString"].ConnectionString;
DataSet dataSet = new DataSet();
// Create connection object
//OleDbConnection oleConn = new OleDbConnection(connString);
SqlConnection oleConn = new SqlConnection(connString);
try
{
oleConn.Open();
string sql = "SELECT TOP (50) Driver.FirstName + Driver.LastName AS DriverName, Booking.BookingId, Driver.CarId AS CarUsed, Booking.CreateDateTime AS BookingDateTime, Booking.Status FROM Booking INNER JOIN Customer ON Booking.CustomerId = Customer.CustomerId INNER JOIN Driver ON Booking.DriverId = Driver.DriverId ORDER BY Booking.BookingId DESC";
SqlDataAdapter dataAdapter = new SqlDataAdapter(sql, oleConn);
dataAdapter.Fill(dataSet, "Booking");
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
oleConn.Close();
}
if (dataSet.Tables.Count <= 0)
return null;
else
return dataSet;
}
数据库中以字符串形式保存日期和时间的列是CreationTime。
是否可以通过调用DecodeTime方法在sql中编码这些时间并将其显示到gridview。
答案 0 :(得分:2)
可以使用String.Format
方法实现。
像往常一样将GridView绑定到数据源,并在标记中声明模板列,如下所示。
<asp:TemplateField HeaderText="Date">
<ItemTemplate>
<%# String.Format("{2}/{1}/{0} {3}:{4}:00",
Eval("ColName").Split('@') ) %>
</ItemTemplate>
<asp:TemplateField>
答案 1 :(得分:0)
SqlDataAdapter / DataTable / DataColumn不提供任何拦截值并将其类型更改为DateTime的机制(您只能将某些内容转换为自定义类)。最好的办法是在SQL查询中进行转换(尽管字符串函数相当有限,因此查询会很长)。
另一种选择是在返回之前向表中添加一个新的DateTime列,并遍历每一行以调用您的方法。
if (dataSet.Tables.Count == 0)
return null;
dataSet.Tables[0].Columns.Add(new DataColumn("CreationTime2", typeof(DateTime)));
foreach (var r in dataSet.Tables[0].Rows)
r["CreationTime2"] = DecodeTime(r["CreationTime"]);
return dataSet;