[英]How to write SQL to display short date and time
I'm building a web application in asp.net using C# and postgreSQL database. 我正在使用C#和postgreSQL数据库在asp.net中构建Web应用程序。 The application is a booking system for appointments.
该应用程序是用于约会的预订系统。
In a listbox I print the date, time and name of a certain appointment. 在列表框中,我打印某个约会的日期,时间和名称。 I get get the date, time and name from the database.
我从数据库中获取日期,时间和名称。 My problem is that the date and time displays in long format, see picture below.
我的问题是日期和时间以长格式显示,请参见下图。
I want to display date in format 2014-04-22 and time in format 08:00 . 我想以2014-04-22格式显示日期,以08:00格式显示时间。
My code: 我的代码:
string sql = "SELECT date, time, name FROM tbl_app WHERE id = '" + id + "'";
NpgsqlCommand command = new NpgsqlCommand(sql, conn);
NpgsqlDataReader dr = command.ExecuteReader();
while (dr.Read())
{
Listbox.Items.Add(dr["date"] + " " + dr["time"] + " " + dr["name"]);
}
Not really sure how the formatting could be done at Postgres end, but the fields appear to be of type DateTime
, you can format the DateTime
objects in your C# code like: 不太确定如何在Postgres末尾进行格式化,但是这些字段似乎是
DateTime
类型的,您可以在C#代码中格式化DateTime
对象,例如:
while (dr.Read())
{
//Check for DBNull.Value
DateTime date = Convert.ToDateTime(dr["date"]);
DateTime time = Convert.ToDateTime(dr["time"]);
Listbox.Items.Add(date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture) + " "
time.ToString("HH:mm", CultureInfo.InvariantCulture) + " "
+ dr["name"]);
}
Consider using parameter with your Query instead of concatenating your query. 考虑在查询中使用参数 ,而不是串联查询。 This is prone to SQL Injection .
这很容易发生SQL注入 。 You may see: Custom Date and Time Format Strings
您可能会看到: 自定义日期和时间格式字符串
You can use ToShortDateString
and ToShortTimeString
which work on strings, which is why I used ToString
on the DataReader items 您可以使用对字符串有效的
ToShortDateString
和ToShortTimeString
,这就是为什么我在DataReader项上使用ToString
原因
while (dr.Read())
{
Listbox.Items.Add(dr["date"].ToString().ToShortDateString() + " " + dr["time"].ToString().ToShortTimeString() + " " + dr["name"]);
}
http://msdn.microsoft.com/en-us/library/system.datetime.toshorttimestring.aspx http://msdn.microsoft.com/en-us/library/system.datetime.toshortdatestring.aspx http://msdn.microsoft.com/en-us/library/system.datetime.toshorttimestring.aspx http://msdn.microsoft.com/en-us/library/system.datetime.toshortdatestring.aspx
Edit 编辑
As the comment points out ToShortDateString does exist on Strings, instead it's applied to DateTime values... Code updated to show how 正如注释所指出的,ToShortDateString确实存在于字符串上,而是应用于DateTime值...更新了代码以显示如何
while (dr.Read())
{
Listbox.Items.Add(
DateTime.Parse(dr["date"].ToString()).ToShortDateString() + " " +
DateTime.Parse(dr["time"].ToString()).ToShortTimeString() + " " +
dr["name"]);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.