How to write SQL to display short date and time - c#

I'm building a web application in asp.net using C# and postgreSQL database. 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.
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:
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. 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
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
Edit
As the comment points out ToShortDateString does exist on Strings, instead it's applied to DateTime values... Code updated to show how
while (dr.Read())
{
Listbox.Items.Add(
DateTime.Parse(dr["date"].ToString()).ToShortDateString() + " " +
DateTime.Parse(dr["time"].ToString()).ToShortTimeString() + " " +
dr["name"]);
}

Related

How Can I insert Only Date in the Database C#

//I have this code and I want to insert only the date in the database without //the time, but this will always store value like this: 2019-10-19 00:00:00.000.
SqlCommand cmd2 = conn.CreateCommand();
cmd2.CommandType = CommandType.Text;
DateTime date = DateTime.ParseExact(TextBox_DepartureDate.Text, "dd/MM/yyyy", null);
DateTime date2 = DateTime.ParseExact(TextBox_ArrivalDate.Text, "dd/MM/yyyy", null);
string time1 = TextBox_DepartureTime.Text + " " + DropDownListAMPM.SelectedValue;
string time2 = TextBox_ArrivalTime.Text + " " + DropDownList_AMPM2.SelectedValue;
DateTime dateOnly1 = date.Date;
DateTime dateOnly2 = date2.Date;
if (date <= DateTime.Now.Date)
{
Label_EditTableMessage.ForeColor = System.Drawing.Color.Red;
Label_EditTableMessage.Text = "Departure Date Cannot be in the past";
}
else
{
if (date2 <= date)
{
Label_EditTableMessage.ForeColor = System.Drawing.Color.Red;
Label_EditTableMessage.Text = "Return Date Cannot be Less than the Departure Date";
}
else
{
cmd2.CommandText = "insert into flight(airline_id,flight_number,numer_seats,departure_city,destination_city,departure_time,arrival_time,departure_date,arrival_date) values( '" + DropDownList_AirlineId.SelectedValue + "','" + TextBox_FlightNumber.Text + "','" + TextBox_NumerSeats.Text + "', '" + TextBox_DepartureCity.Text + "', '" + TextBox_DestinationCity.Text + "', '" + time1 + "', '" + time2 + "', '" + dateOnly1 + "', '" + dateOnly2 + "') ";
cmd2.ExecuteNonQuery();
Label_EditTableMessage.ForeColor = System.Drawing.Color.Green;
Label_EditTableMessage.Text = "Flight Added";
EmptyTextBoxes();
GridView_Flight.DataBind();
}
}
}
The problem is not with your code. You should change the data type of your field in the database. Instead of datetime or datetime2 you should use date.
You can refer to this article: https://learn.microsoft.com/en-us/sql/t-sql/functions/date-and-time-data-types-and-functions-transact-sql?view=sql-server-ver15#DateandTimeRelatedTopics
2 parts to this:
Your schema probably has the column data type set to DATETIME instead of just DATE which is going to cause it to store the full date and time regardless. This is the first thing I would check.
In your C# you can use the .Date property on a DateTime object to get just the date part of it. This is irrelevant if you use the correct data type for your column as per point 1
date.Date
or if you want it in string format:
date.Date.ToShortDateString()
the problem is you use
DateTime dateOnly1 = date.Date;
DateTime dateOnly2 = date2.Date;
and previus you use
DateTime date = DateTime.ParseExact(TextBox_DepartureDate.Text, "dd/MM/yyyy", null);
DateTime date2 = DateTime.ParseExact(TextBox_ArrivalDate.Text, "dd/MM/yyyy", null);
you are working only with date, and the datetime assume the time with 00:00:00

Errors when inserting date and time into QODBC query C#

I am getting an error
ERROR [42500] ERROR: 3020 - There was an error when converting the date value "0000-00-48. In the field "salesOrder Transaction Date
The date value I am trying to insert is 4/4/2018.
My code
DateTime JobDate = Wintac_JobDate;
string addSalesOrder = "INSERT INTO SalesOrderLine (CustomerRefListID, TemplateRefListID," +
" SalesOrderLineItemRefListID, SalesOrderLineDesc,SalesOrderLineQuantity, SalesOrderLineRate, " +
"SalesOrderLineSalesTaxCodeRefListID, Memo, SalesOrderLineInventorySiteRefListID, SalesOrderLineInventorySiteLocationRefListID" +
", TxnDate, ShipAddressAddr1, ShipAddressAddr2, ShipAddressAddr3, ShipAddressAddr4, ShipAddressAddr5, FQSaveToCache)" +
"VALUES('" + QBCustomerListID + "','" + templateLID + "', '" + LID + "', '" + Description + "', " + Quantity + ", " + 120 + "," +
" '" + SalesTax + "', '" +Wintac_WipNo+"','"+LaborSite+"','"+LaborSiteLocation+"',"+
"?,'" + shipAdr1+ "','" + shipAdr2 + "','" + shipAdr3 + "','" + shipAdr4 + "','" + shipAdr5 + "'," +
""+ FQSaveToCache + ")";
OdbcCommand sqlcmd2 = new OdbcCommand(addSalesOrder, quickbookscon2);
sqlcmd2.CommandType = CommandType.Text;
sqlcmd2.CommandTimeout = 180;
MessageBox.Show(JobDate.ToShortDateString());
sqlcmd2.Parameters.Add("P7", OdbcType.DateTime).Value = JobDate
if (Quantity != 0)
{
if (sqlcmd2.ExecuteNonQuery() == 1)
{
if(FQSaveToCache == 0)
MessageBox.Show(" added successfully.");
}
}
sqlcmd2.Dispose()
I have tried converting the variable Job Date
Date Time
short date string
long date string
entering the variable directly into the query
Any help would be appreciated.
I think the main problem is on that line;
sqlcmd2.Parameters.Add("P7", OdbcType.DateTime).Value = JobDate.ToLongDateString()
You try to insert string representation on a DateTime typed column. That's quite wrong. You need to directly pass your DateTime value instead of passing it string representation. To learn this as a habit, please read Bad habits to kick : choosing the wrong data type
Other than this, I saw a few problem also in your code:
You should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
Use using statement to dispose your connection and commmand automatically instead of callind Dispose method manually which you didn't even consider to do in your code.

updating data in MySql database table

I am creating a Windows Forms application and now at certain point I need to make a database connection, I have inserted the values to database easily, but now its not updating my data, I am using following query for this purpose:
MySqlCommand sda = new MySqlCommand(#"Update shedulling.tablelayout1 set date = '"
+ date + "',line = " + line + ",col1 = '" + first_textbox.text + "', col2 = '"
+ sec_textbox.text + "',col3_textbox.text = '" + thi_textbox.text
+ "',col4_textbox.text = '" + four + "' where date = '" + date + "' AND line = '"
+ line.ToString() + "' ", conn);
conn is a connection string which is written fine, and date and line are string and integer values send as an argument to this function.
You have missed single quotes in line part. Change it like this line = '" + line + "'.
Also there is one more notable thing in your code: you are trying to find the record in the table that is not exist yet in where clause where date = '" + date + "' AND line = '" + line.ToString() + "' note in this line date and line are the new values not old values so no rows affected in the update query. You should use old values of date and line in the where clause.
Also you should always use parameterized queries. This kind of string concatenations are open for SQL Injection.
Try debugging the code, there must be INSERT statement executing somewhere in your code.
UPDATE: If "line" is integer variable then you need to convert it into string. You have converted it after WHERE clause but not after SET clause.
You may want to post some more code to get exact answer.

C#: comparing datetimepicker with MS access date

I am using ms access as database that contains field identified as (short date)
i inserted time to that field from datetimepicker in C# using the following query:
string query = #"insert into category_in (category_id,amount_in,dates)
values ('" + ids + "','" + amount2 + "','"+dateTimePicker1.Text+"')";
and everything is ok. But when i am trying to compare the date in the database with date from another datetimpicker it doesnot work. This is the query of comparsion:
query = "SELECT products.category, category_in.dates FROM products, category_in where " +
"category_in.dates>= " + dateTimePicker1.Value.Date.ToShortTimeString() + " "
"and category_in.dates<= " + dateTimePicker2.Value.Date.ToShortTimeString() + "";
when i use dateTimePicker.value.Date it gives me the following error
Syntax error (missing operator) in query expression
'category_in.dates>= 16/08/2015 12:00:00 ص and category_in.dates<=
20/08/2015 12:00:00 ص
but when i add dateTimePicker.value.Date.ToShortTimeString no results returned although there are some data between these dates
do i have to change the insertion method?
I'm surprised that all three answers (so far) have suggested that you continue using dynamic SQL and fiddle with your string-formatted dates and delimiters until you get something that works.
That's just dumb.
The DateTimePicker control returns a System.DateTime value so you should just use that as part of a parameterized query, something like this:
using (var conn = new OdbcConnection(
#"Driver={Microsoft Access Driver (*.mdb, *.accdb)};" +
#"Dbq=C:\Users\Public\Database1.accdb"))
using (var cmd = new OdbcCommand("INSERT INTO MyTable (DateTimeField) VALUES (?)", conn))
{
conn.Open();
cmd.Parameters.Add("?", OdbcType.DateTime).Value = dateTimePicker1.Value.Date;
cmd.ExecuteNonQuery();
}
I think your code should use the # delimiter for date expressions in Access:
string query = #"insert into category_in (category_id,amount_in,dates)
values ('" + ids + "','" + amount2 + "',#" + DateTime.Parse(dateTimePicker1.Text).ToString("yyyy'/'MM'/'dd") + "#)";
and:
query = "SELECT products.category, category_in.dates FROM products, category_in where " +
"category_in.dates >= #" + dateTimePicker1.Value.Date.ToString("yyyy'/'MM'/'dd") + "# "
"and category_in.dates <= #" + dateTimePicker2.Value.Date.ToString("yyyy'/'MM'/'dd") + "#";
Try changing your query to this:
query = "SELECT products.category, category_in.dates FROM products, category_in where " +
"category_in.dates>= #" + dateTimePicker1.Value.ToShortDateString() + "# "
"and category_in.dates<= #" + dateTimePicker2.Value.ToShortDateString() + "#";
The issue is your dates are strings. Add Single quotes before and after your datetime values. Like this...
query = "SELECT products.category, category_in.dates FROM products, category_in where " +
"category_in.dates>= '" + dateTimePicker1.Value.Date.ToShortTimeString() + "' "
"and category_in.dates<= '" + dateTimePicker2.Value.Date.ToShortTimeString() + "'";
This will allow the query engine to implicitly convert the strings to datetimes.

Unable to insert DateTime format into database

I'm unable to insert the DateTime into my database. Am i writing the statement wrongly?
Apparently without the DateTime, I am able to insert into the database
string dateAndTime = date + " " + time;
CultureInfo provider = CultureInfo.InvariantCulture;
DateTime theDateTime = DateTime.ParseExact(dateAndTime, "d MMMM yyyy hh:mm tt", provider);
//Create a connection, replace the data source name with the name of the SQL Anywhere Demo Database that you installed
SAConnection myConnection = new SAConnection("UserID=dba;Password=sql;DatabaseName=emaDB;ServerName=emaDB");
//open the connection
; myConnection.Open();
//Create a command object.
SACommand insertAccount = myConnection.CreateCommand();
//Specify a query.
insertAccount.CommandText = ("INSERT INTO [meetingMinutes] (title,location,perioddate,periodtime,attenders,agenda,accountID,facilitator,datetime) VALUES ('"+title+"','" + location + "', '" + date + "','" + time + "', '" + attender + "','" + agenda + "', '" + accountID + "','" + facilitator + "','" +theDateTime+ "')");
try
{
insertAccount.ExecuteNonQuery();
if (title == "" || agenda == "")
{
btnSubmit.Attributes.Add("onclick", "displayIfSuccessfulInsert();");
//ScriptManager.RegisterStartupScript(this, GetType(), "error", "alert('Please ensure to have a title or agenda!');", true);
}
else
{
btnSubmit.Attributes.Add("onclick", "displayIfSuccessfulInsert();");
Response.Redirect("HomePage.aspx");
//ScriptManager.RegisterStartupScript(this, this.GetType(), "Redit", "alert('Minutes Created!'); window.location='" + Request.ApplicationPath + "/HomePage.aspx';", true);
}
}
catch (Exception exception)
{
Console.WriteLine(exception);
}
finally
{
myConnection.Close();
}
It does not insert the SQL into my database.
PS: theDateTime for example, may a value which is 7/14/2012 1:35:00 AM. How to insert this into the database??
Yes, you should write the query with parameters {0}, {1}, etc, and then use Parameters.Add.
insertAccount.CommandText = ("INSERT INTO [meetingMinutes]
(title,location,perioddate,periodtime, ...)
VALUES (?,?,?,?, ... )");
insertAccount.Parameters.Add( ... );
This will ensure that the SQL gets formed with correct syntax; and also prevent SQL injection attacks.
First of all NEVER use string concatenation for SQL queries or commands. Use parameters.
If you will use parameters then:
it is not possible to make sql-injection
query text and plan is cached, which increases performance
and what is important in your case - you do not have to think about formatting of the value, just pass the DateTime variable as the parameter
And also crosscheck that your DB column has datetime2 type, otherwise most likely you will not be able to store values less than 1 Jan 1758 (e.g. DateTime.MinValue).
Dont use quotes for yr date, remove all quotes where you are using a date
change ,'" +theDateTime+ "') to ," +theDateTime+ ")
and also secure yr sql cause it unsave for SQL injections

Categories